Javascript 如何删除url页面上的#id
请帮助我在url浏览器上删除或隐藏我的#id 例如:Javascript 如何删除url页面上的#id,javascript,jquery,html,css,.htaccess,Javascript,Jquery,Html,Css,.htaccess,请帮助我在url浏览器上删除或隐藏我的#id 例如: 我在“p1”上的菜单1目标 我的网站“mysite.com/index.htm” 当我点击浏览器上的菜单1时,我会看到“mysite.com/index.htm#p1” 我不需要在url浏览器上显示我的id,只需要“mysite.com/index.htm”而不是像这样的“mysite.com/index.htm#p1” #p1:target{background:red;} #p2:目标{背景:绿色;} #p3:目标{背景:蓝色;}
- 我在“p1”上的菜单1目标
- 我的网站“mysite.com/index.htm”
- 当我点击浏览器上的菜单1时,我会看到“mysite.com/index.htm#p1”
#p1:target{background:red;}
#p2:目标{背景:绿色;}
#p3:目标{背景:蓝色;}
#p4:目标{背景:黄色;}
#p5:目标{背景:珊瑚;}
#p6:目标{背景:天蓝色;}
ul{列表样式类型:无;
保证金:0;
填充:0;
溢出:隐藏;
背景色:#333;
}
li{float:左;}
LIA{显示:内联块;
颜色:白色;
文本对齐:居中;
填充:14px 16px;
文本装饰:无;}
李娜:停下来{
背景色:#111;
}
第1页
第2页
第3页
第4页
第5页
Page6
有几种方法可以做到这一点,我最喜欢的是制作一个自定义功能,在页面链接中滚动到,而不是依赖浏览器。
像这样
$("a[href^='#']").click(function(e){
e.preventDefault();
var elem = $($(this).attr('href'));
/* check for broken link */
if(elem.length)
$(window).animate('scrollTop' , elem.offset().top)
})
除了从url中隐藏“#id”之外,它还可以设置滚动动画
希望能有所帮助。我知道这个问题在互联网时代已经开始过时了,但我想我会与大家分享我的解决方案(这是基于Janmajay Agrawal的解决方案) 它基本上取代了超链接的标准行为,并创建了到所需元素的平滑滚动 这段代码使用“香草”JS,应该适用于大多数web浏览器
//Get all the hyperlink elements
var links = document.getElementsByTagName("a");
//Browse the previously created array
Array.prototype.forEach.call(links, function(elem, index) {
//Get the hyperlink target and if it refers to an id go inside condition
var elemAttr = elem.getAttribute("href");
if(elemAttr && elemAttr.includes("#")) {
//Replace the regular action with a scrolling to target on click
elem.addEventListener("click", function(ev) {
ev.preventDefault();
//Scroll to the target element using replace() and regex to find the href's target id
document.getElementById(elemAttr.replace(/#/g, "")).scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});
});
}
});
如果此代码不正确,请随时指出 您无法使用
.htaccess
从URL获取/替换#whatever
,因为它未解析到服务器。为什么要这样做?#锚的要点是,用户可以使用它直接链接到页面上的某个点。可能重复您正在使用的可能重复项,因此它将作为超链接工作并重定向。尝试使用jQuery的click事件,您将得到答案。