这是一个现场演示:
http://jsbin.com/vewavayexa/edit?output
我建议你把代码复制到本地看看效果,它们不适合jsbin元素,有时它不能加载所有图像(如果是刷新你的浏览器)
<header>
<h1>Gallery</h1>
</header>
<nav><a href="Home">Home</a><a href="">Blog</a><a href="">About</a></nav>
<div class="gallery">
<div class="container">
<img src="https://i.loli.net/2018/03/06/5a9d82e150523.jpg" alt="">
<img src="https://i.loli.net/2018/03/06/5a9d82e1bd5b0.jpg" alt="">
<img src="https://i.loli.net/2018/03/06/5a9d82e203fc3.jpg" alt="">
<img src="https://i.loli.net/2018/03/06/5a9d82e1be833.jpg" alt="">
</div>
</div>
<footer>Copyright</footer>
css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul {
list-style: none;
}
a {
text-decoration: none;
color:#FFF;
}
a:hover {
background:#B7023F;
}
header {
height: 70px;
background:#55024A;
color: #FFF;
}
h1 {
line-height: 70px;
padding: 0 30px;
}
nav {
background: #E16639;
padding: 0 15px;
color: #FFF;
height: 50px;
}
nav a {
/* height: 50px; */
/* line-height: 50px; */
display: inline-block;
padding: 15px 15px;
}
footer {
height: 70px;
line-height: 70px;
background: #AD860A;
color: #FFF;
padding: 0 30px;
}
img {
display: block;
position: absolute;
}
.gallery {
overflow: hidden;
position: relative;
}
.container {
top: 0;
left: 0;
position: absolute;
}
js
const wh = getWH()
const gallery = document.querySelector('.gallery')
const container = document.querySelector('.container')
gallery.style.width = wh.w + 'px'
gallery.style.height = wh.h + 'px'
container.style.height = wh.h + 'px'
let imgs = document.querySelectorAll('img')
const allImgWidth = []
container.appendChild(imgs[0].cloneNode(true))
container.insertBefore(imgs[imgs.length -1].cloneNode(true), imgs[0])
imgs = document.querySelectorAll('img')
// set width and height for each images
Array.prototype.forEach.call(imgs, img => {
if (parseInt(img.clientWidth) > parseInt(img.clientHeight)) {
img.style.width = wh.w + 'px'
} else {
img.style.height = wh.h + 'px'
}
img.style.left = allImgWidth.reduce((a, b) => a + b, 0 )
allImgWidth.push(img.offsetWidth)
})
const totalWidth = allImgWidth.reduce((a, b) => a + b, 0)
container.style.width = totalWidth + 'px'
const slideWidth = totalWidth - allImgWidth[allImgWidth.length - 1]
const step = parseInt(slideWidth / 100)
let startPoint = container.style.left = -allImgWidth[0]
// move container, if it got max left, then reset to starting point
setInterval(() => {
let x = container.style.left.slice(0, -2) - step
if (Math.abs(x) >= slideWidth) {
container.style.left = startPoint
} else {
container.style.left = x
}
}, 100)
function getWH() {
const header = document.querySelector('header')
const nav = document.querySelector('nav')
const footer = document.querySelector('footer')
const offset = header.offsetHeight + nav.offsetHeight + footer.offsetHeight
return {
w: window.innerWidth,
h: document.body.clientHeight - (header.offsetHeight + nav.offsetHeight + footer.offsetHeight)
}
}