如何获得与浏览器分辨率相同的元素



我正在尝试使用jquery将元素的高度设置为等于用户浏览器。 这是我到目前为止得到的代码,它不起作用。是因为我在 css 中设置了最小高度吗?我真的需要这个类来等于用户分辨率。

<script type="text/javascript">
jQuery(function() { 
    jQuery(".bg").css("height", jQuery(window).css("height"));
}
</script>

将变量设置为window.innerHeight

$(document).ready(function() {
    var height = window.innerHeight;
    $(".bg").css("height", height);
});

有关window.innerHeight的更多详细信息,请参阅:https://developer.mozilla.org/en-US/docs/DOM/window.innerHeight。

window.innerHeight返回用户视区的高度,而不是您询问的屏幕分辨率,但它有效。还有window.innerWidth和其他方法可以抓取用户的屏幕统计信息。

您也可以使用 self.innerHeightparent.innerHeighttop.innerHeight ,但它们有不同的用途。(见链接)。

此外,您正在使用$(window).css("height"); jQuery css()函数分配 css 值,它不返回字符串。这将是$(window).height(),因为height()确实返回了一个字符串。

var height = function() { return this.length; }
// height() returns "this.length"

试试这个,它会保持图像的纵横比

$(function(){
var ratio = $("img").width() / $("img").height();
var newWidth = ($(window).height()-10) * ratio;
if(newWidth > $(window).width())
        $("img").css("width","100%");
    else
        $("img").css("width",newWidth+"px");
$(window).resize(function(){
    var ratio = $("img").width() / $("img").height();
    var newWidth = $(window).height() * ratio;
    if(newWidth > $(window).width()){
        $("img").css("width","100%");
        }
    else{
        $("img").css("width",newWidth+"px");
        }
});
});
你必须

使用jQuery(window).height() .Windows实际上没有随分辨率变化的动态高度css属性。

要将"元素"高度设置为您需要的窗口高度。

$('element').height($(window).height());

您可以使用此JavaScript脚本来获取浏览器的高度和宽度。它还支持多种浏览器:

var viewportwidth;
var viewportheight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
    viewportwidth = window.innerWidth,
    viewportheight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
    viewportwidth = document.documentElement.clientWidth,
    viewportheight = document.documentElement.clientHeight
}
// older versions of IE
else {
    viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
    viewportheight = document.getElementsByTagName('body')[0].clientHeight
}

浏览器的宽度和高度将分别存储在viewportwidthviewportheight变量中。然后,您可以使用类似

var bg = document.getElementById("bg");
bg.style.height = viewportheight;

这会将 id bg 高度的元素设置为视口高度。

相关内容

最新更新