js拖動實現左右圖片對比效果

admin發表於2017-04-15

分享一段程式碼例項,它實現了通過拖動實現左右圖片光線對比效果。

先不說這樣的功能有沒有實用性,不過看起來挺不錯的,就分享一下。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
.left {
  float: left;
}
#topDiv {
  width: 540px;
  height: 295px;
  position: relative;
  margin-right: 30px;
}
#original {
  width: 100%;
  height: 100%;
  background: url(demo/js/img/serenity.JPG) no-repeat;
}
#effect {
  position: absolute;
  top: 0;
  left: 0;
  width: 300px;
  height: 295px;
  z-index: 100;
  background: url(demo/js/img/cinematic.JPG) no-repeat;
  border-right: 1px solid #fff;
}
#effect > span {
  display: inline-block;
  width: 20px;
  height: 20px;
  position: absolute;
  top: 150px;
  right: -10px;
  z-index: 200;
  cursor: pointer;
  background: url("demo/js/img/drag.png") no-repeat;
}
#effectImageDiv li {
  float: left;
  width: 55px;
  height: 70px;
  cursor: pointer;
  list-style: none;
}
#effect1 {
  background: url(demo/js/img/cinematic.png) no-repeat;
}
#effect2 {
  background: url(demo/js/img/mono.png) no-repeat;
}
#effect3 {
  background: url(demo/js/img/analog.png) no-repeat;
}
</style>
<script>
window.onload = function() {
  function getId(id) {
    var ele = document.getElementById(id);
    return ele;
  }
  getId("drag").onmousedown = function(e) {
    e = e || window.event;
    document.onmousemove = function(e) {
      e = e || window.event;
 
      if (e.clientY < 290 && e.clientX < 540 && e.clientY > 0 && e.clientX > 0) {
        getId("drag").style.top = e.clientY + "px";
        getId("effect").style.width = e.clientX + 'px';
      }
 
    }
  }
  document.onmouseup = function() {
    document.onmousemove = null;
    document.onmosuseup = null;
  }
  getId("effect1").onclick = function() {
    getId("effect").style.background = "url(demo/js/img/cinematic.JPG) no-repeat"
  }
  getId("effect2").onclick = function() {
    getId("effect").style.background = "url(demo/js/img/mono.JPG) no-repeat"
  }
  getId("effect3").onclick = function() {
    getId("effect").style.background = "url(demo/js/img/analog.JPG) no-repeat"
  }
}
</script>
</head>
<body>
  <div id="topDiv" class="left">
    <div id="original"></div>
    <div id="effect"><span id="drag" class="left"></span> </div>
  </div>
  <div id="effectImageDiv" class="left">
    <h2>點選這裡切換圖片效果 </h2>
    <br />
    <br />
    <ul>
      <li class="effect" id="effect1"></li>
      <li class="effect" id="effect2"></li>
      <li class="effect" id="effect3"></li>
 
    </ul>
  </div>
</body>
</html>

相關文章