Home >Web Front-end >JS Tutorial >Implementation of javascript picture sliding effect_javascript skills

Implementation of javascript picture sliding effect_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:32:432069browse

This article shares with you how to implement the JavaScript image sliding effect. The specific content is as follows. Let’s take a look at the rendering first:

Mouse over that picture to display the complete picture. If you remove it, it will be reset:

Simple CSS and JS operation DOM implementation:

<!doctype html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>sliding doors</title>
  <link rel="stylesheet" href="styles/reset.css" />
  <link rel="stylesheet" href="styles/slidingdoors.css" />
  <script src="scripts/slidingdoors.js"></script>
 </head>
 <body>
  <div id='container'>
   <img src="images/door1.png" alt="Implementation of javascript picture sliding effect_javascript skills" title="Implementation of javascript picture sliding effect_javascript skills" />
   <img src="images/door2.png" alt="5.5寸四核" title="5.5寸四核" />
   <img src="images/door3.png" alt="四核5寸" title="四核5寸" />
   <img src="images/door4.png" alt="5.7寸机皇" title="5.7寸机皇" />
  </div>
 </body>
</html>

css:

#container {
 height: 477px;
 margin: 0 auto;
 border-right: 1px solid #ccc;
 border-bottom: 1px solid #ccc;
 overflow: hidden;
 position: relative;
}

#container img {
 position: absolute;
 display: block;
 left: 0;
 border-left: 1px solid #ccc;
}

js operation:

window.onload = function() {
 //容器对象
 var box = document.getElementById('container');

 //获得图片NodeList对象集合
 var imgs = box.getElementsByTagName('img');

 //单张图片的宽度
 var imgWidth = imgs[0].offsetWidth;

 //设置掩藏门体露出的宽度
 var exposeWidth = 180;

 //设置容器总宽度
 var boxWidth = imgWidth + (imgs.length - 1) * exposeWidth;
 box.style.width = boxWidth + 'px';

 //设置每道门的初始位置
 function setImgsPos() {
  for (var i = 1, len = imgs.length; i < len; i++) {
   imgs[i].style.left = imgWidth + exposeWidth * (i - 1) + 'px';
  }
 }
 setImgsPos();

 //计算每道门打开时应移动的距离
 var translate = imgWidth - exposeWidth;

 //为每道门绑定事件
 for (var i = 0, len = imgs.length; i < len; i++) {
  //使用立即调用的函数表答式,为了获得不同的i值
  (function(i) {
   imgs[i].onmouseover = function() {
    //先将每道门复位
    setImgsPos();
    //打开门
    for (var j = 1; j <= i; j++) {
     imgs[j].style.left = parseInt(imgs[j].style.left, 10) - translate + 'px';
     //imgs[j].style.left = j*exposeWidth +"px";
    }
   };
   imgs[i].onmouseout = function(){
    setImgPos();
   };
  })(i);
 }
}; 

I hope this article will be helpful to everyone learning JavaScript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn