页面中的浮动框

第一种

<style>

    #img{

        position: absolute;

        top: 0;

        left: 0;

        width: 100px;

        height: 100px;

    }

</style>

<body>

   

    <img src="./image/1.jpg" id="img" >

    <script>

        //3、浮动广告(页面中一张广告图片不断的变化位置)

        let image = document.getElementById('img');

        function float() {

            image.style.transition = 'all 1s linear';

            let r = Math.trunc(Math.random() * (screen.width - image.width))

            image.style.left = `${r}px`

            r = Math.trunc(Math.random() * (screen.height - image.height))

            image.style.top = `${r}px`

        }

        setInterval(float, 1000)

    </script>

</body>

第二种

<style>

    #dt {

        width: 200px;

        height: 150px;

        position: absolute;

    }

</style>

<body>

    <div id="dt">

        <img src="./image/1.jpg" alt="" width="200" height="150">

    </div>

    <script>

        function updatePosition() {

            //1.获取随机数

            let my_top = Math.random() * 600

            let my_left = Math.random() * 1000

            //2.获取div

            let div = document.querySelector('#dt')

            div.style.top = my_top + 'px'

            div.style.left = my_left + 'px'

        }

        setInterval(updatePosition, 1000)

    </script>

</body>

第三种

<style>

  * {

    margin: 0;

    padding: 0;

  }

  body {

    position: relative;

    height: 100vh;

  }

  img {

    position: absolute;

    height: 100px;

    width: 160px;

  }

</style>

</head>

<body>

  <img src="./image/1.jpg" />

  <script>

    const img = document.querySelector('img');

    const body = document.querySelector('body');

    const w = body.offsetWidth;

    const h = body.offsetHeight;

    let left = 0,

      up = 0;

    let leftBorder = true,

      upBorder = true;

    setInterval(() => {

      if (left === 0) leftBorder = true;

      if (up === 0) upBorder = true;

      if (left === w - img.offsetWidth) leftBorder = false;

      if (up === h - img.offsetHeight) upBorder = false;

      leftBorder ? left++ : left--;

      upBorder ? up++ : up--;

      img.style.left = left + 'px';

      img.style.top = up + 'px';

    }, 1);

  </script>

</body>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值