js,jQuery实现可关闭悬浮框广告特效,兼容(谷歌,火狐,Ie)

注意不能直接用close()命名关闭广告函数,避免冲突。

javascript实现方法:

<!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>无标题文档</title>
    <style type="text/css">
        #apDiv1 {
            position: absolute;
            left: 251px;
            top: 51px;
            width: 529px;
            height: 210px;
            z-index: 2;
            background-color: #0000FF;
        }

        #closebt {
            position: absolute;
            top: 0;
            right: 0;
            background: red;
        }

        #apDiv2 {
            position: absolute;
            left: 128px;
            top: 381px;
            width: 912px;
            height: 18663px;
            z-index: -1;
            background-color: #FF0000;
        }

        -->
    </style>
    <script>
        var xx = 0;
        function init() {//获取元素的top值
            xx = document.getElementById("apDiv1").offsetTop;
        }
        function aa() {
            if (document.body.scrollTop) {//兼容谷歌
                document.getElementById("apDiv1").style.top = xx + document.body.scrollTop + "px";
            } else {//兼容ie,火狐
                document.getElementById("apDiv1").style.top = xx + document.documentElement.scrollTop + "px";
            }
        }
        window.onscroll = aa;
        function closetext() {
            document.getElementById("closebt").style.display="none";
            document.getElementById("apDiv1").style.display="none";
        }
    </script>
</head>

<body onload="init()">
<div id="apDiv1">
    <span id="closebt"><a href="#" onclick="closetext()">可关闭</a></span>
</div>
<div id="apDiv2"></div>
</body>
</html>

 jquery实现方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #main {
            text-align: center;
        }

        #adver {
            position: absolute;
            left: 50px;
            top: 30px;
            z-index: 2;
        }
    </style>
    <script src="js/jquery-1.11.3.min.js"></script>
    <script>
        var advertop;
        $(function () {
             advertop=$("#adver").position();//获取到div style中的top值
        })
        $(window).scroll(function () {
            var wintop=$(this).scrollTop();//获取窗口滚动条的top距离
            var x=wintop+advertop;//x用来存储div style中的top值+窗口滚动条的top距离
            $("#adver").css("top",x);//用x重新设置div的css中的top值
        })
    </script>
</head>
<body>
<div id="adver"><img src="images/adv.jpg"/></div>
<div id="main"><img src="images/main1.jpg"/><img src="images/main2.jpg"/><img src="images/main3.jpg"/></div>
</body>
</html>

 

posted @ 2017-06-28 14:26  斯丢皮德曼  阅读(1869)  评论(0编辑  收藏  举报