1. 程式人生 > 實用技巧 >原生js實現圖示移動點選裝向

原生js實現圖示移動點選裝向

程式碼如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">

        #slider {
            width: 1600px;
            height: 300px;
            margin: 0 auto;
            margin-top: 100px;
            border: 1px solid black
; overflow: hidden; } #content { width: 99999999px; height: 400px; } img { margin-right: 10px; cursor: pointer; background-size: 100% 100%; } #button { width: 100px; margin
: 20px auto; } </style> </head> <body> <div id="slider"> <div id="content"> <img src="img/1.png"/> <img src="img/2.png"/> <img src="img/3.png"/> <img src="img/4.png"/> </div> </div> <div id="button"
> <button type="button" id="left">向左</button> <button type="button" id="right">向右</button> </div> <script type="text/javascript"> var content = document.getElementById("content"); var left = document.getElementById("left"); var right = document.getElementById("right"); content.style.marginLeft = 0 + "px"; content.innerHTML = content.innerHTML + content.innerHTML + content.innerHTML; var key = "run"; var dkey;//修改的地方 var rkey;//修改的地方 content.onmouseover = function () { key = "stop"; } content.onmouseout = function () { key = "run"; }
  //修改 left.onclick
= function () { dkey = "left"; rkey = '' }
  //新增的函式 right.onclick
= function () { rkey = "right"; dkey = '' } //向右移動需要設定 function dd() { var num = parseFloat(content.style.marginLeft); if (dkey == "left") { if (key == "run") { num -= 1; if (num <= -170 * 5) { num = 0; } } //向右移動 }
      //新增
if (rkey == "right") { if (key == "run") { num += 0.5; if (num <= -170 * 5) { num = 0; } } //向右移動 } content.style.marginLeft = num + "px"; setTimeout("dd()", 13); } dd(); </script> </body> </html>