欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS實(shí)現(xiàn)點(diǎn)擊按鈕隨機(jī)生成可拖動(dòng)的不同顏色塊示例

 更新時(shí)間:2019年01月30日 10:07:59   作者:waterDjj  
這篇文章主要介紹了JS實(shí)現(xiàn)點(diǎn)擊按鈕隨機(jī)生成可拖動(dòng)的不同顏色塊,涉及javascript數(shù)值運(yùn)算與頁面元素屬性動(dòng)態(tài)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了JS實(shí)現(xiàn)點(diǎn)擊按鈕隨機(jī)生成可拖動(dòng)的不同顏色塊。分享給大家供大家參考,具體如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.dbjr.com.cn JS點(diǎn)擊生成隨機(jī)顏色塊</title>
<style type="text/css">
div{
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  margin-left: 10px;
  float: left;
}
</style>
</head>
<body id="body1">
<button onclick="btn()">創(chuàng)建div</button>
<script>
  function btn(){
    var id;
    //動(dòng)態(tài)創(chuàng)建元素
    var str=document.createElement("div");
    //元素的背景色隨機(jī)的
    str.style.backgroundColor=getColorRandom();
    //將生成的div追加到body中
    document.getElementById("body1").appendChild(str);
    //隨機(jī)生成的id設(shè)置為動(dòng)態(tài)創(chuàng)建的div的id
    str.id="items"+parseInt(Math.random()*10000);
    // 獲取動(dòng)態(tài)生成的div的id
    var obj=document.getElementById(str.id);
    var disX=0;
    var disY=0;
    //鼠標(biāo)點(diǎn)擊落下事件
    obj.onmousedown=function (event){
      disX=event.clientX-obj.offsetLeft;
      disY=event.clientY-obj.offsetTop;
      //鼠標(biāo)移開事件
      document.onmousemove=function(ev){
        obj.style.left=ev.clientX-disX+"px";
        obj.style.top=ev.clientY-disY+"px";
      }
      //鼠標(biāo)松開事件
      document.onmouseup= function () {
        document.onmousemove=null;
        document.onmouseup=null;
      }
    }
    //生成隨機(jī)顏色
    function getColorRandom(){
      var c="#";
      var cArray=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
      for(var i=0;i<6;i++){
       var cIndex= Math.round(Math.random()*15);
        c+=cArray[cIndex];
      }
      return c;
    }
  }
</script>
</body>
</html>

這里使用在線HTML/CSS/JavaScript代碼運(yùn)行工具http://tools.jb51.net/code/HtmlJsRun測(cè)試上述代碼,可得如下運(yùn)行效果:

更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript頁面元素操作技巧總結(jié)》、《JavaScript操作DOM技巧總結(jié)》、《JavaScript切換特效與技巧總結(jié)》、《JavaScript動(dòng)畫特效與技巧匯總》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)

希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論