我需要使用 css 表达式从 css 中找出并应用平板电脑宽度。我有一个 div 内容。它应该在纵向模式下应用宽度 100%,当我转向横向时,div 应该将宽度更改为平板设备宽度的一半(平板电脑宽度/2)。如何在 css 中应用这种表达方式?
问问题
1265 次
1 回答
2
我会尽量避开表达式,因为它们仅限于 Internet Explorer 5,6 和 7(什么平板电脑运行这个??),并且它们大大减慢了速度(性能方面)。无论如何,试试这个:
@media screen and (orientation:portrait) {
/* Portrait styles */
}
@media screen and (orientation:landscape) {
.element {
width:expression(document.body.clientWidth / 2);
}
}
您还可以尝试更多细节 - 这些将被视为黑客(感谢 TheBlackBenzKid 的建议):
/* Windows 7 Phone - WP7 */
@media only screen and (max-device-width: 480px) and (orientation:portrait) {
}
@media only screen and (max-device-width: 480px) and (orientation:landscape) {
}
/* Apple iPhone */
@media only screen and (max-device-width: 320px) and (orientation:portrait) {
}
@media only screen and (max-device-width: 320px) and (orientation:landscape) {
}
如果不使用表达式(例如,针对其他浏览器和..好吧,平板电脑),您可以使用一个小的 javascript 来检测方向,然后向元素添加一个类:
html:
<body onorientationchange="updateOrientation();">
Javascript:
function updateOrientation() {
if(window.innerWidth> window.innerHeight){
//we are in landscape mode, add the 'LandscapeClass' class to the element
document.getElementById("element").className += " LandscapeClass";
} else {
//we are in portrait mode, remove the class
document.getElementById("element").className =
document.getElementById("element").className.replace
( /(?:^|\s)LandscapeClass(?!\S)/ , '' );
}
如果使用 jQuery,你可以试试这个,直接修改元素的(内联)CSS:
function updateOrientation() {
var $width;
if(window.innerWidth> window.innerHeight){
$width = window.innerWidth/2;
} else {
$width = '100%';
}
$(".element").css({width:$width});
}
我还没有测试过这些,但我认为它会起作用
于 2012-07-20T07:44:44.673 回答