JavaScript自學筆記(3)--- 用JS來實現網頁浮窗

 

最近作個小項目,給網頁加個浮窗,考驗了基礎的css,js技術,仍是蠻有意思的,代碼以下(部分代碼來源於引用,見底部)javascript

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    *{
        padding: 0;
        margin: 0;
    }
    body {
        height: 900px;
		background-color: white;
    }
    .fl {
        width: 200px;
        height: 100px;
        background-color:white;
        position: fixed;
    }
div
{
	    border-style:solid;
	    border-top-color:#84C1FF;
	    border-top-width:22px;
}

</style>
<body>
   
    <div class="fl" id="fl">
	<b>注意:</b>  "border-top-width" 單獨使用沒有效果. 要先使用 "border-style" 屬性設置 borders.
    </div>
</body>



<script language=javascript>

var fl = document.getElementById('fl');

var chroX = document.documentElement.clientWidth;//yemian整個的高寬
var chroY = document.documentElement.clientHeight;

var offsetLeft = fl.offsetLeft;//盒子的位置
var offsetTop = fl.offsetTop;

var timer = 0;//起始秒錶爲0

//console.log(offsetTop)

var x = 1;//每次移動一
var y = 1;

window.onresize = function(){
    chroX = document.documentElement.clientWidth;//yemian整個的高寬
    chroY = document.documentElement.clientHeight;
}

function move(){
    offsetLeft += x;
    offsetTop += y;
    fl.style.left = offsetLeft  + 'px';
    fl.style.top = offsetTop  + 'px';
    //console.log(chroY)
}
window.onload = function(){
   timer = setInterval(function(){
        move();
        if(offsetTop+200 > chroY || offsetTop < 0){
            y = -y;
        }
        if(offsetLeft+200 > chroX || offsetLeft <0){//若是離網頁邊框不到200就反方向移動
            x = -x;
        }
    },30)//調整速度,間隔(數字)越大越慢
}
fl.onmouseenter = function(){
    clearInterval(timer)  //鼠標放在浮窗上就中止移動
}
fl.onmouseleave = function(){//鼠標移開從新開始移動
    window.onload();
}

</script>
</html>

  

大致思路就是設定一個計時器,每到一個時間就從新顯示一次窗口,由於你的座標不一樣,並且刷新的時間是以毫秒爲單位在進行,因此就顯示出了一種浮窗的效果。css

 

 

引用:https://blog.csdn.net/qq_22849785/article/details/93596680 html

相關文章
相關標籤/搜索