测试客户端是否支持 css prop。重复后代码中断

Testing if css prop is supported by the client. Code breaks after repetitions

如果有人知道为什么我的代码在我多次 运行 时中断/无限循环,故意导致结果 'false'[=12,我将非常感激=]

警告如果您 运行 带有 invalid/unsupported css 属性的代码,您的浏览器可能会停止响应。

<!DOCTYPE html>
<html>
<body>

<p>Test if a style property is supported by the browser.</p>

<form onsubmit="myFunction(); return false">
<input type="text" id="prop" style="width: 180px;" placeholder="e.g. box-shadow">
<button type="submit">Try it</button>
</form>

<p id="demo"></p>

<script>
String.prototype.isSupported = (function() { 
    var div = document.createElement('div'), 
        vendors = 'khtml ms o moz webkit'.split(' '), 
        len = vendors.length; 

    return function(prop) { 
        prop = this.valueOf(); 
        if(prop in div.style) return true; 
        prop = prop.replace(/^[a-z]/, function(val) { return val.toUpperCase(); }); 
        while(len--) { 
            if(vendors[len] + prop in div.style) { return true; } 
        } 
        return false; 
    }; 
}) ();

function myFunction() {
    var input = document.getElementById("prop").value;
    document.getElementById("demo").innerHTML = input.isSupported();
}
</script>

</body>
</html>

每次调用 isSupported() 函数时,您都需要重置 len 值。现在您的代码建议您仅在声明 isSupported() 方法时收集长度。因此,在第一次调用之后,您的 while 循环使 len 变量变为 0。然后任何后续调用都会进一步递减 len 变量并将其变为 -1、-2,依此类推。在 JS 中负值是真实的。所以,你的 while 循环卡住了。您需要做的就是在调用函数时重置 len 变量。这是固定代码: https://jsfiddle.net/f3kpdwu4/4/

String.prototype.isSupported = (function() { 
    var div = document.createElement('div'), 
        vendors = 'khtml ms o moz webkit'.split(' '), 
        len = vendors.length; // it runs only once

    return function(prop) { 
        len = vendors.length; // refresh it on every call
        prop = this.valueOf(); 
        if(prop in div.style) return true; 
        prop = prop.replace(/^[a-z]/, function(val) { return val.toUpperCase(); }); 
        while(len--) { 
            if(vendors[len] + prop in div.style) { return true; } 
        } 
        return false; 
    }; 
}) ();