点击锚点时自动回到页面顶部

3

我有一个问题,

当我将页面滚动到中间时,点击右侧的a标签显示div后,页面会自动滚动到页面顶部。我想要阻止这种情况的发生,

请帮忙!谢谢。

我的源代码:https://codepen.io/lhthuong181/pen/OJPxpxB

-html

<div id="container">
<a href="#">
<img 
onclick="showCustom()"id="setting"src="https://images.unsplash.com/photo157530259766162aae7fe1447? 
ixlib=rb- 
1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ">
</a>
<div id="custom"  class="custom-1">

</div>

</div>

-Css

  #custom {
position: fixed;
width: 100px;
height: 200px;
right: 20px;
top: 100px;
background-color: white;
transition: 0.8s;
border-radius: 20px;

}
.custom-1 {

right: -150px !important;


}
#setting {
position: fixed;
width: 30px;
z-index: 99;
right: 30px;
top: 50px;
background-color: rgb(255, 255, 255);
padding: 5px;
border-radius: 15px;
}

#container {
background-color:black;
width:100%;
height:2000px;
}

-Js

var btnsetting = document.getElementById("setting");
function showCustom() {
var x = document.getElementById("custom");
if (x.className == "" ) {

    x.className = "custom-1";

}

else{


    x.className = "";


}}

https://codepen.io/lhthuong181/pen/OJPxpxB

2个回答

3

欢迎来到SO

href 中使用 JavaScript:Void(0); 而不是 #

替换

 <a href="JavaScript:Void(0);">
<img 
onclick="showCustom()"id="setting"src="https://images.unsplash.com/photo157530259766162aae7fe1447? 
ixlib=rb- 
1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ">
</a>

参考 https://www.quackit.com/javascript/tutorial/javascript_void_0.cfm

该链接介绍了JavaScript中的void(0)。在JavaScript中,void运算符会对给定的表达式进行求值并返回undefined。void(0)通常用于避免浏览器跳转到一个新页面,因为它不会执行任何操作。

是的...非常感谢,喜欢你的Ref <3 - Hoài

2
你应该移除 "a" 元素并使用 cursor: pointer 来达到相同的效果。
HTML:
    <div id="container">

                <img onclick="showCustom()" id="setting" src="https://images.unsplash.com/photo-1575302597661-62aae7fe1447?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ">

            <div id="custom"  class="custom-1">

            </div>

    </div>

CSS(层叠样式表):
  #custom {
    position: fixed;
    width: 100px;
    height: 200px;
    right: 20px;
    top: 100px;
    background-color: white;
    transition: 0.8s;
    border-radius: 20px;

  }
  .custom-1 {

    right: -150px !important;


  }
  #setting {
    position: fixed;
    width: 30px;
    z-index: 99;
    right: 30px;
    top: 50px;
    background-color: rgb(255, 255, 255);
    padding: 5px;
    border-radius: 15px;
    cursor: pointer;
  }

  #container {
    background-color:black;
    width:100%;
    height:2000px;
  }

以下是展示内容: https://codepen.io/jeroldlin/pen/rNaGyoW


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接