一、需求
箭头图标按钮,使用PNG图片,需要用4张切图来展示按钮的4种状态:normal、hover、pressed、forbidden
二、实现
方法可能比较笨,但目前只想到这一种方法,记录一下。
上代码
...
<div class="imgPart1">
<div class="imgPart1-1">
<img class="img" id="first" src="normal.png" alt="#"/>
<img class="img" id="firstHover" src="hover.png" alt="#"/>
<img class="img" id="firstPressed" src="pressed.png" alt="#"/>
<img class="img" id="firstForbidden" src="forbidden.png" alt="#"/>
</div>
<div class="imgPart1-2">
<img class="img" id="last" src="imgs/ic_next_normal.png" alt="#"/>
<img class="img" id="lastHover" src="imgs/ic_next_hover.png" alt="#"/>
<img class="img" id="lastPressed" src="imgs/ic_next_pressed.png" alt="#"/>
<img class="img" id="lastForbidden" src="imgs/ic_next_forbidden.png" alt="#"/>
</div>
</div>
...
.img{
display: none;
}
// 给img父元素的div绑定鼠标事件
function bindMouseEvent(className){
const div = document.querySelector(className)
div.onmouseover=(e)=>{
const childrenList = [...e.target.parentNode.children]
if(childrenList[0].style.display==='block'){
childrenList[0].style.display = 'none'
childrenList[1].style.display = 'block'
}
}
div.onmousedown=(e)=>{
const childrenList = [...e.target.parentNode.children]
if(childrenList[1].style.display==='block'){
childrenList[1].style.display = 'none'
childrenList[2].style.display = 'block'
}
}
div.onmouseup=(e)=>{
const childrenList = [...e.target.parentNode.children]
if(childrenList[2].style.display==='block'){
childrenList[2].style.display = 'none'
childrenList[1].style.display = 'block'
}
}
div.onmouseout=(e)=>{
const childrenList = [...e.target.parentNode.children]
if(childrenList[1].style.display==='block'){
childrenList[1].style.display = 'none'
childrenList[0].style.display = 'block'
}
}
}
bindMouseEvent(".imgPart1-1")
bindMouseEvent(".imgPart1-2")