我有一个if语句,可以调整背景视频的大小以匹配浏览器窗口的高度和宽度,但有时它不起作用,并且只会匹配高度或宽度。我相对肯定这可以通过确保if子句和else子句无论如何运行来解决。我考虑过将它嵌套在for循环中,但这似乎不是一个好的解决方案。
这是我的代码。
JS:
var resizeVideo = function() {
var fullWidth = window.innerWidth;
var fullHeight = window.innerHeight;
var video = document.getElementById("test");
var videoWidth = video.style.width;
var videoHeight = video.style.height;
console.log(videoHeight);
console.log(fullHeight);
var fired = false;
if(parseInt(video.style.height, 10) <= window.innerHeight && fired == false) {
video.style.height = fullHeight + 'px';
var fullWidthAdjusted = fullHeight * 1.7777777;
video.style.width = fullWidthAdjusted + 'px';
console.log(videoWidth);
console.log("Height correction working");
fired = true;
} else {
video.style.width = fullWidth + 'px';
var fullHeightAdjusted = fullWidth * .5625;
video.style.height = fullHeightAdjusted + 'px';
console.log("Width correction working");
fired = true;
}
};
window.onresize = resizeVideo;
window.onload = resizeVideo;
答案 0 :(得分:2)
if .. else
可以执行一段代码或另一段代码。在您的情况下,两者都可能需要执行,具体取决于具体情况,因此您需要两个单独的if语句,每个语句都有自己的条件。
// You can, but don't have to, introduce a variable for this.
// I like it, because it makes the condition more readable and a bit more
// self-documenting, but you might just as well put it in the 'if' as you did.
var heightChanged = parseInt(video.style.height, 10) <= window.innerHeight;
var widthChanged = parseInt(video.style.width, 10) <= window.innerWidth;
if (heightChanged) {
video.style.height = fullHeight + 'px';
var fullWidthAdjusted = fullHeight * 1.7777777;
video.style.width = fullWidthAdjusted + 'px';
console.log(videoWidth);
console.log("Height correction working");
}
if (widthChanged) {
video.style.width = fullWidth + 'px';
var fullHeightAdjusted = fullWidth * .5625;
video.style.height = fullHeightAdjusted + 'px';
console.log("Width correction working");
}
我删除了'fired'变量,因为它在你的代码中没有真正做任何事情。
或者,您可能希望查看文章Proportional Resizing of Web Page Elements Using Only CSS。