使用javascript更改浏览器调整大小的背景css

Use javascript to change background css on browser resize

本文关键字:背景 css 调整 javascript 浏览器 使用      更新时间:2023-09-26

所以,当浏览器高度等于浏览器宽度的2/3时,我想改变background-size。这是我试过的代码,但我不能让它工作。

<body id="body" onresize="BG_resize()">
<script>
    function BG_resize() {
        var w = window.innerWidth;
        var h = window.innerHeight;
        if ((w * (2 / 3)) < h){
            document.getElementById("body").style.background-size = "auto 100%";
        }
    }
</script>
</body>
css:

#body {
    background:url("Layout/BG.jpg");
    background-size:100% auto;
}

你的JS应该使用backgroundSize,而不是background-size:

document.getElementById("body").style.backgroundSize = "auto 100%";

所有这些的另一个替代方法是使用媒体查询(因为您正在窗口上执行此操作)并一起摆脱javascript。这将运行得更流畅,因为浏览器会为你完成大部分工作。

看起来你正在寻找的查询是长宽比,所以像这样:

@media screen and (min-aspect-ratio: 2/3) 
{
   body {
      background-size: auto 100%;
   }
}
@media screen and (max-aspect-ratio: 2/3) 
{
   body {
      background-size: 100% auto;
   }
}

我发现另一个更容易的选择是使用jQuery。可以简单地使用resize()事件处理程序。下面是一个例子:

$(window).on('resize', function () {

//在这里你可以添加你想在调整大小时执行的代码})

要改变css,你也可以使用jQuery .css().

http://fofwebdesign.co.uk/template/_...tio-resize.htm

.target-ratio-resize {
	max-width: 960px; /* actual img width */
	max-height: 150px; /* actual img height */
	*height: 150px; /* actual img height - IE7 */
	background-image: url(students.jpg);
	background-size: cover;
	background-position: center;
}
.target-ratio-resize:after {
	content: " ";
	display: block; 
	width: 100%; 
	padding-top: 66.666%; /* 2:3 ratio */
}