溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2021-04-20 09:49:28 來源:億速云 閱讀:264 作者:小新 欄目:web開發(fā)

小編給大家分享一下JS如何實(shí)現(xiàn)點(diǎn)擊按鈕隨機(jī)生成可拖動的不同顏色塊示例,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

JS是什么

JS是JavaScript的簡稱,它是一種直譯式的腳本語言,其解釋器被稱為JavaScript引擎,是瀏覽器的一部分,主要用于web的開發(fā),可以給網(wǎng)站添加各種各樣的動態(tài)效果,讓網(wǎ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.jb51.net 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;
    //動態(tài)創(chuàng)建元素
    var str=document.createElement("div");
    //元素的背景色隨機(jī)的
    str.style.backgroundColor=getColorRandom();
    //將生成的div追加到body中
    document.getElementById("body1").appendChild(str);
    //隨機(jī)生成的id設(shè)置為動態(tài)創(chuàng)建的div的id
    str.id="items"+parseInt(Math.random()*10000);
    // 獲取動態(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測試上述代碼,可得如下運(yùn)行效果:

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

看完了這篇文章,相信你對“JS如何實(shí)現(xiàn)點(diǎn)擊按鈕隨機(jī)生成可拖動的不同顏色塊示例”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

js
AI