BOM中的Location.hash用法

一、当前页面:可以通过location.hash进行设置

 location.hash = 'sss'
            console.log(location.hash);

设置后可以通过location.hash访问

会将该值拼接到url上

用法:在要跳转的html元素上设置name属性,然后设置location.hash值就可以实现页面内跳转。注意:如果跳转后如果location.hash不清空就无法继续跳转。

<html>

<head>
    <style>
        .box {
            width: 200px;
            height: 3000px;
            background-color: pink;
        }
        
        .box2 {
            width: 100px;
            height: 200px;
            background-color: black;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <a name="sss">ssss</a>
    <script type="text/javascript">
        var box = document.querySelector('.box');
        box.addEventListener('click', function() {
            location.hash = 'sss'
            console.log(location.hash);
        });
    </script>
</body>

</html>

2、跳转到其他页面

w3c中给出的例子:

  var x = window.open("test.html", "", "scrollbars=yes,width=250,height=200")
             x.location.hash = '3';

实测通过这种方式location.hash的值无法在浏览器控制台显示,并且url后面也没有location.hash的值(有没有懂的解释下)

解决方案:(1)直接在当前页面拼接url地址

var x = window.open("test.html#sss", "", "scrollbars=yes,width=250,height=200")

(2)在跳转页面通过load事件给location.hash赋值

 window.addEventListener('load', function() {
            // location.hash = 3;
            console.log(location.hash);
        })

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值