如何使用Javascript检测窗口宽度
这就是我到目前为止得到的:如何使用Javascript检测窗口宽度,javascript,html,window,width,Javascript,Html,Window,Width,这就是我到目前为止得到的: <!DOCTYPE html> <html> <head> <title>Fonts!</title> <link rel="stylesheet" href="fonts.css"> </head> <body> <h1 id="Hagin">Hello.</h1> <h2 id="Hagin2">Goo
<!DOCTYPE html>
<html>
<head>
<title>Fonts!</title>
<link rel="stylesheet" href="fonts.css">
</head>
<body>
<h1 id="Hagin">Hello.</h1>
<h2 id="Hagin2">Goodbye.</h2>
<p class="Glober">Hello. This is a paragraph. It is meant to test this font. What do you think? Do you like this font? I think I do, although I'm not sure. That's why I'm writing this paragraph. Eh? Bigger you say? I agree. Let's make it bigger. Yeah, you know what, I'm using this. Allong with that Hagin thing. Some sexy shit.</p>
<div></div>
<script type="text/javascript">
var width = window.innerWidth;
if (width < (300 + "px")) {
window.alert("It works!");
}
</script>
</body>
</html>
当窗口下降到300像素以下时,什么也不会发生。我在用谷歌浏览器。我也试过了
if (width < 300) {
但这也不起作用。想法?试试
window.onresize = function(event) {
var width = window.innerWidth;
if (width < 300) {
alert("It works!");
}
};
这将在每次调整窗口大小时触发事件。我认为这里的问题在于条件语句。我认为javascript不理解如何将窗口宽度(基本整数和字符串300px)进行比较。尝试删除条件的+px位,使其如下所示:
var width = window.innerWidth;
if (width < (300)) {
window.alert("It works!");
}
这应该能奏效
var resized;
$(window).on('resize orientationChanged', function(){
clearTimeout(resized);
resized = setTimeout(function () {
var width = window.innerWidth;
if (width < 300) {
window.alert("It works!");
}
}, 200);
});
这可能会起作用。当页面加载时,代码只执行一次,然后再也不会执行。您需要将该代码附加到事件处理程序,以便根据需要执行它以响应事件,例如调整窗口大小。如何执行?我将使用什么事件处理程序?也许整个文件都要交给我?看起来很烦人。。。