有一个应用领域是目前的CSS尚且无能为力的。如果我们想随着时间的变化而不断改变某个元素的样式,则只能使用JavaScript。JavaScript能够按照预定的时间间隔重复调用一个函数,而这意味着我们可以随着时间的推移而不断改变某个元素的样式。
通过css我们可以很轻松控制元素的位置,但是想要实现随时间的变化位置也方式位移这些还不够
function ele_postion() {
const h1 = document.getElementById("h")
h1.style.position = "absolute"
h1.style.left = "200px"
h1.style.top = "200px"
}
这样元素的位置将会在5秒后跳转到js设置的位置上,在此期间我们可以使用clearTimeout(time)清除时间
虽然元素发生了位移但是会有些僵硬这离动画效果还是差了点
var time=setTimeout(ele_postion,5000)
function ele_postion() {
const h1 = document.getElementById("h")
h1.style.position = "absolute"
h1.style.left = "200px"
h1.style.top = "200px"
}
var time = null
ele_postion()
function ele_postion() {
const h1 = document.getElementById("h")
h1.style.position = "absolute"
let cur_x = parseInt(h1.style.left)||0
let cur_y = parseInt(h1.style.top)||0
if(cur_x==200&&cur_y==200){
clearTimeout(time)
return true;
}
if (cur_x < 200) {
cur_x++
}
if (cur_x > 200) {
cur_x--
}
if (cur_y < 200) {
cur_y++
}
if (cur_y > 200) {
cur_y--
}
h1.style.left = cur_x + "px"
h1.style.top = cur_y + "px"
time = setTimeout(ele_postion, 30)
}
var time = null
ele_postion(document.getElementById("h"),200,200,30)
function ele_postion(dom,target_x,target_y,timer) {
dom.style.position = "absolute"
let cur_x = parseInt(dom.style.left)||0
let cur_y = parseInt(dom.style.top)||0
if(cur_x==target_x&&cur_y==target_y){
clearTimeout(time)
return true;
}
if (cur_x < target_x) {
cur_x++
}
if (cur_x > target_x) {
cur_x--
}
if (cur_y < target_y) {
cur_y++
}
if (cur_y > target_y) {
cur_y--
}
dom.style.left = cur_x + "px"
dom.style.top = cur_y + "px"
time = setTimeout(function(){
ele_postion(dom,target_x,target_y,timer)
}, timer)
}
现在我们需要在此HTML结构上当鼠标移动到链式上就展示对应的图片,当图片第一次被加载即便是高速网络也会有一定的延迟我们现在来解决这个问题
既然是初次加载的时候会有延迟,那么我们就从这个方向出发。干脆直接让图片一次性加载完毕不需要显示的部分用css属性隐藏起来,当需要显示的时候就用css控制显示
- 由于书上给的代码实在是太老,也看不懂所有我就按照自己的思路实现了一个
// html部分
Web Design
Lorem ipsum dolor sit amet consectetur adipisicing.
// css部分
.overhiden {
width: 100px;
height: 100px;
overflow: hidden;
position: relative;
display: flex;
}
li {
width: fit-content;
}
img {
flex-shrink: 0;
transition: all .7s;
}
// js部分
let lis = document.getElementsByTagName("li");
let imgs = document.getElementsByTagName("img");
lis = Array.from(lis)
imgs = Array.from(imgs)
lis.forEach((item, index) => {
item.addEventListener("mouseenter", () => {
imgs.forEach((sub) => {
sub.style.transform = `translate(${-(index * 100)}px)`
})
})
})