javascript - 达到屏幕的最大宽度后图像没有停止
问题描述
我的问题是:当图像达到用户的最大屏幕宽度时,如何阻止图像向左移动?我使用 JavaScript 尝试了以下方法,但它不起作用。此外,当图像达到用户的最大宽度时,它应该改变方向并返回到之前的位置。
<img src="plane.jpg" width="100px" height="100px" id="plane">
<script type="text/javascript">
var height = document.documentElement.clientHeight;
var width = document.documentElement.clientWidth;
var plane = document.getElementById("plane");
var leftpos = 0;
setInterval(function(){
if (leftpos != width) {
leftpos += 10;
plane.style.marginLeft = leftpos + 'px'
}else {
// change the direction
}
}, 50) // run code every 50 milliseconds
;
</script>
珍惜你的时间并保重。
解决方案
您可以检查图像加 10 的marginLeft
和width
是否小于window.innerWidth
。
var height = document.documentElement.clientHeight;
var width = window.innerWidth;
var plane = document.getElementById("plane");
var leftpos = 0;
var right = true;
var id = setInterval(function() {
if (right && leftpos + plane.width + 10 <= width) {
leftpos += 10;
} else {
right = false;
leftpos -= 10;
if (leftpos <= 0) clearInterval(id);
}
plane.style.marginLeft = leftpos + 'px';
}, 50);
<img src="plane.jpg" width="100px" height="100px" id="plane">
推荐阅读
- python-3.x - “无法写入关闭传输”是什么意思?
- https - 使用 https 的 Windows 主机文件?
- python - 在 Django 中过滤嵌套的相关对象
- docker - 如何在 Windows 上更改 rabbitmq 持久消息位置?
- sql - 使用空字段查询时出现“找不到属性”访问错误
- android - 构建位于 skia/platform_tools/android 目录下的示例应用程序查看器时出错
- android - 类不能继承AndroidViewModel,为什么?
- ios - 在 Xamarin iOS 中拒绝位置权限时应用程序崩溃
- excel - 如果另一列等于值,则将单元格从一列复制到剪贴板的宏
- c++ - C++ 多级继承 - 调用基本构造函数错误