JavaScript中“if statement”的前半部分只触发一次

First half of 'if statement' in javascript is only firing once

本文关键字:一次 if statement 前半部 JavaScript      更新时间:2023-09-26

我有 if/else 语句,我正在使用它来调整背景视频的大小,尽管我遇到了一个错误,即语句if(video.style.height <= window.innerHeight && fired == false)的第一部分仅在页面大小调整时触发一次...... 语句的后半部分,else部分将连续触发,没有错误。 你们有什么理由看到吗? 我有点像JavaScript菜鸟,所以很抱歉,如果这是显而易见的事情。

.JS:

window.onresize = 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(video.style.height <= window.innerHeight && fired == false) {
        video.style.height = fullHeight + 'px';
        var fullWidthAdjusted = fullHeight * 1.7777777;
        video.style.width = fullWidthAdjusted + 'px';
        console.log(videoWidth);
        console.log("If statement working");
        fired = true;
    } else {
        video.style.width = fullWidth + 'px';
        var fullHeightAdjusted = fullWidth * .5625;
        video.style.height = fullHeightAdjusted + 'px';
        console.log("Wrong part of statement working");
        fired = true;
    }
};
我不知道

它是否能解决您的问题,但是element.style.height格式为"1234px"字符串,window.innerHeight是像1234一样的数字。

编辑:

而不是video.style.height尝试parseInt(video.style.height, 10).

高度样式是一个字符串,而不是一个数字。在设置样式之前,它将返回一个空字符串,该字符串小于窗口内部高度的字符串表示(隐式转换(,因此执行第一个块。

设置样式后,它将返回附加px的高度,并且不小于窗口内部高度的字符串表示形式,因此执行第二个块。

可以使用 parseInt 方法将样式获取为数字:

if(parseInt('0' + video.style.height, 10) <= window.innerHeight && fired == false) {

字符串之前'0' +是使您首先获得的空字符串变为零。否则,它将NaN并且比较将失败。

因为 if 语句中的第二个条件是 fired === false ,这在第一次调整大小后不成立,因为您在 ifelse块中都设置了fired = true

如果您希望它多次触发,请删除&& fired === false