滚动视图
效果:
图片会在红色方框中随着鼠标移动而滚动
制作方法:
1.将红色方框作为bigbox 是 可视窗口宽度有限, 而box是放置图片的无限宽度的,在bigbox中设置 overflow 就可以让多出来的图片部分隐藏,给box盒子添加 display:flex;可以让图片水平展示,给bigbox盒子添加position:relative属性 给图片添加position:absolute属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
#bigbox {
height: 500px;
width: 1000px;
position: relative;
border: solid 1px red;
border-radius: 40px;
box-shadow: 3px 0 4px #cccccc;
margin: 0 auto;
overflow: hidden;
}
#box {
display: flex;
align-items: center;
position: absolute;
}
#box li {
margin: 0px 50px;
float: left;
list-style: none;
}
#box img {
border-radius: 30px;
width: 300px;
}
</style>
</head>
<body>
<div id="bigbox">
<ul id="box">
<li>
<img src="img/img1.jpg" alt="">
</li>
<li>
<img src="img/img8.jpg" alt="">
</li>
<li>
<img src="img/Mikasa3.jpg" alt="">
</li>
<li>
<img src="img/mikasa4.jpg" alt="">
</li>
<li>
<img src="img/mikasa5.jpg" alt="">
</li>
<li>
<img src="img/mikasa6.jpg" alt="">
</li>
</ul>
</div>
</body>
</html>
2.JavaScript部分:通过改变box.style.left的值实现 图片的移动;因为拖动box时 left 必须要累加才能实现一直拖动 所以通过 box的offsetleft (box到父盒子的距离)来代表上一次拖动的距离;必须要用onmouseover表示放开鼠标的事件 因为 需要图片每时每刻都跟这鼠标动
要提前删除图片的移动链接
<script>
var bigbox = document.querySelector('#bigbox');
var box = document.querySelector('#box');
var bigboxW = bigbox.offsetWidth;
var img = document.querySelectorAll('img');
// 禁止图片默认的拖动链接
for (let i = 0; i < img.length; i++) {
img[i].onmousedown = function(e) {
e.preventDefault();
}
}
box.onmousedown = function(e) {
var X1 = e.clientX;
var offsetleft = box.offsetLeft; //offsetleft表示拒父盒子的距离
box.onmouseover = function(e2) {
var X2 = e2.clientX;
var L = X2 - X1;
if (offsetleft + L > 0) {
return //当盒子左端到头了
} else if (offsetleft + L < -(boxW - bigboxW)) {
return
} else {
box.style.left = offsetleft + L + 'px';
}
}
document.onmouseup = function() {
box.onmousemove = null;
box.onmouseup = null;
}
}
</script>