一、需求

箭头图标按钮,使用PNG图片,需要用4张切图来展示按钮的4种状态:normal、hover、pressed、forbidden

二、实现

方法可能比较笨,但目前只想到这一种方法,记录一下。

上代码

  1. ...
  2. <div class="imgPart1">
  3. <div class="imgPart1-1">
  4. <img class="img" id="first" src="normal.png" alt="#"/>
  5. <img class="img" id="firstHover" src="hover.png" alt="#"/>
  6. <img class="img" id="firstPressed" src="pressed.png" alt="#"/>
  7. <img class="img" id="firstForbidden" src="forbidden.png" alt="#"/>
  8. </div>
  9. <div class="imgPart1-2">
  10. <img class="img" id="last" src="imgs/ic_next_normal.png" alt="#"/>
  11. <img class="img" id="lastHover" src="imgs/ic_next_hover.png" alt="#"/>
  12. <img class="img" id="lastPressed" src="imgs/ic_next_pressed.png" alt="#"/>
  13. <img class="img" id="lastForbidden" src="imgs/ic_next_forbidden.png" alt="#"/>
  14. </div>
  15. </div>
  16. ...
  1. .img{
  2. display: none;
  3. }
  1. // 给img父元素的div绑定鼠标事件
  2. function bindMouseEvent(className){
  3. const div = document.querySelector(className)
  4. div.onmouseover=(e)=>{
  5. const childrenList = [...e.target.parentNode.children]
  6. if(childrenList[0].style.display==='block'){
  7. childrenList[0].style.display = 'none'
  8. childrenList[1].style.display = 'block'
  9. }
  10. }
  11. div.onmousedown=(e)=>{
  12. const childrenList = [...e.target.parentNode.children]
  13. if(childrenList[1].style.display==='block'){
  14. childrenList[1].style.display = 'none'
  15. childrenList[2].style.display = 'block'
  16. }
  17. }
  18. div.onmouseup=(e)=>{
  19. const childrenList = [...e.target.parentNode.children]
  20. if(childrenList[2].style.display==='block'){
  21. childrenList[2].style.display = 'none'
  22. childrenList[1].style.display = 'block'
  23. }
  24. }
  25. div.onmouseout=(e)=>{
  26. const childrenList = [...e.target.parentNode.children]
  27. if(childrenList[1].style.display==='block'){
  28. childrenList[1].style.display = 'none'
  29. childrenList[0].style.display = 'block'
  30. }
  31. }
  32. }
  33. bindMouseEvent(".imgPart1-1")
  34. bindMouseEvent(".imgPart1-2")