[英]window.innerWidth in JavaScript
here's my code: 这是我的代码:
<body>
<header></header>
<div id="slider" class="slider">
<p>Slider content</p>
</div>
<script src="jas.js"></script>
</body>
var divPos = 50;
var direction = "L";
function preparepage() {
document.getElementById("slider").style.position = "absolute";
document.getElementById("slider").style.left = divPos + "px";
document.getElementById("slider").style.top = "50px";
animateDiv = setInterval(beginAnimate,50);
}
function beginAnimate () {
if (direction == "L") {
divPos+=50;
if (divPos == 1300) {
direction = "R";
}
} else if (direction == "R"){
divPos-=50;
if (divPos == 150) {
direction = "L";
}
}
document.getElementById("slider").style.left = divPos + "px";
}
window.onload = function () {
setTimeout(preparepage,200);
};
I want #slider to go from left to right and when it reaches certain point to go back. 我希望#slider从左向右移动,并在到达某个点时返回。 My code works fine, but I tried it this way:
我的代码工作正常,但是我尝试了这种方式:
if (direction == "L") {
divPos+=50;
if (divPos == window.innerWidth - 300) {
direction = "R";
}
}
and it goes left for ever. 它永远消失了。 Why is that happening?
为什么会这样呢? What can I do to make it go back at certain point, no what what screen resolution is?
我该怎么做才能使其返回特定点,而不是什么屏幕分辨率?
Use: 采用:
if (divPos > window.innerWidth - 300) {
Unless the window's width is a multiple of 50, incrementing divPos
by 50 won't hit innerWidth - 300
exactly, so you need to be less exacting. 除非窗口的宽度是50的倍数,否则将
divPos
增加50不会精确地达到innerWidth - 300
,因此您需要降低精确度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.