标签:lse ansi mamicode osi ali cti offset hid display
在展示框内展示图片,并通过左右按钮平滑的向左向右滑动展示
创建一个外层容器
内层定义使用 transition 进行滑动
点击左右按钮时计算左右滑动距离 使用translateX 进行偏移
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>滑动范例</title>
<style type="text/css">
body {
text-align: center;
}
#view {
text-align: center;
display: inline-block;
border: 5px solid red;
}
.arrow {
width: 20px;
height: 230px;
line-height: 230px;
cursor: pointer;
margin: 5px;
border: 1.5px solid black;
display: inline-block;
background-color: grey;
}
.content {
width: 960px;
min-width: 960px;
position: relative;
height: 230px;
margin: 5px;
overflow: hidden;
display: inline-block;
}
.viewImg {
display: flex;
position: absolute;
left: 0;
transition: transform 0.3s;
}
img {
background-color: blueviolet;
padding: 10px;
width: 200px;
min-width: 200px;
max-width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="view">
<div class="left arrow" onclick="left()"> </div>
<div class="content">
<div class="viewImg" id="viewImg">
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
<img />
</div>
</div>
<div class="right arrow" onclick="right()"></div>
</div>
<script type="text/javascript">
var contentL;
var listL;
var maxL;
var minL;
window.onload = function () {
// 获取容器的宽度
contentL = document.getElementsByClassName('content')[0].offsetWidth;
// 获取内容的宽度
listL = document.getElementsByClassName('viewImg')[0].offsetWidth;
// 判断内容宽度是否大于容器 是否需要左右偏移
if (contentL - listL < 0) {
maxL = contentL - listL;
} else {
maxL = 0;
}
minL = 0;
}
function left() {
// 获取到当前偏移位置
const left_now = document.getElementById('viewImg').style.transform ?
parseFloat(document.getElementById('viewImg').style.transform.substr(11)) : 0;
if (maxL !== 0) {
// 计算需要偏移量 当前偏移 + 440 (两个img的宽度)
const offset = left_now + 440;
if (offset >= minL) {
document.getElementById('viewImg').style.transform = 'translateX(' + minL + 'px)';
} else {
document.getElementById('viewImg').style.transform = 'translateX(' + offset + 'px)';
}
}
}
function right() {
const left_now = document.getElementById('viewImg').style.transform ?
parseFloat(document.getElementById('viewImg').style.transform.substr(11)) : 0;
if (maxL !== 0) {
const offset = left_now - 440;
if (offset <= maxL) {
document.getElementById('viewImg').style.transform = 'translateX(' + maxL + 'px)';
} else {
document.getElementById('viewImg').style.transform = 'translateX(' + offset + 'px)';
}
}
}
</script>
</body>
</html>
标签:lse ansi mamicode osi ali cti offset hid display
原文地址:https://www.cnblogs.com/nhxz001/p/12222463.html