编辑
以下代码获取em的大小,但与我的css不对应。
function doOnOrientationChange() {
// Orientation of device has changed, change the size of map and move the maphelp (if required)
var eminpx = $("#1em").width();
var largescreeninpx = eminpx*66.236;
switch(window.orientation) {
case -90:
case 90:
// Orientation is landscape
console.log('66.236ems in px: ' + largescreeninpx + '. Screen width: ' + screen.height);
$("#map").height(screen.width*0.7); // The screen width is the viewport height of the device because we're in landscape orientation
// Will only work if we can actually get the em value of the width
if (screen.height < largescreeninpx) {
// Small or medium screen, show map help below map
console.log('small screen');
$("#maphelp").css('margin-top', 0);
} else {
// Larger screen, show map and map help side-by-side
$("#maphelp").css('margin-top', -screen.width*0.7);
}
break;
default:
// Orientation is portrait
alert('66.23ems in px: ' + largescreeninpx + '. Screen width: ' + screen.width);
$("#map").height(screen.height*0.7);
// Will only work if we can actually get the em value of the width
if (screen.width < largescreeninpx) {
// Small or medium screen, show map help below map
$("#maphelp").css('margin-top', 0);
} else {
// Larger screen, show map and map help side-by-side
$("#maphelp").css('margin-top', -screen.height*0.7);
}
break;
}
}
尽管在CSS中横向iPad不会触发@media screen and (min-width: 30em) and (max-width: 63.236em) {...}
(这意味着它的宽度超过63.236ems),但在JS中它会触发console.log('small screen')
,显示通过JS获取时屏幕宽度小于66.236ems?
原始问题(几乎回答)我正在尝试围绕"金发姑娘方法"创建一个网站。在电子表格中一切正常,但我正在尝试动态设置嵌入式地图的高度,使其始终是用户当前视口高度的 90%。但是,地图旁边也可能有一些"地图帮助",允许浏览器视口足够大(在本例中为 66.23ems。纵向iPad超过66.23ems)。下面是我的代码,它被注释以显示不起作用的内容。
function doOnOrientationChange() {
// Orientation of device has changed, change the size of map and move the maphelp (if required)
switch(window.orientation) {
case -90:
case 90:
// Orientation is landscape
$("#map").height(screen.width*0.9); // The screen width is the viewport height of the device because we're in landscape orientation
if ($(window).width() > 66.23) { // Need this in ems
// Small or medium screen, show map help below map
$("#maphelp").css('margin-top', 0);
} else {
// Larger screen, show map and map help side-by-side
$("#maphelp").css('margin-top', -screen.width*0.9);
}
break;
default:
// Orientation is portrait
if ($(window).width() < 66.23) { // Need this in ems
// Small or medium screen, show map help below map
$("#maphelp").css('margin-top', 0);
} else {
// Larger screen, show map and map help side-by-side
$("#maphelp").css('margin-top', -screen.height*0.9);
}
break;
}
}
所以,我的问题是,我如何通过检查 ems 来让它触发正确的响应?
按如下方式创建一个范围:
<span id="one_em">M</span>
像这样的 CSS:
#one_em {
display:none;
width: 1em;
}
然后使用 jquery 获取 #one_em 元素的宽度。
const emWidth = $("#one_em").width();
注意:使用 1em 作为 id 会导致某些浏览器无法正确连接 CSS,因为有效的 HTML 4 id
必须以字母开头。 使用M
,使宽度实际上为一米宽。
只需学习在ems和像素之间进行转换,就可以到达您需要去的地方:
https://stackoverflow.com/a/1463032/50358 这个问题是一个很好的答案:ems 和像素之间的关系是什么?