简体   繁体   English

Div在点击时显示,但仅显示一秒钟

[英]Div displays on click but for only a second

I am using onclick method on a link in order to display a div. 我在链接上使用onclick方法以显示div。 However, the div disappears after displaying for a second. 但是,div在显示一秒钟后消失。

 function view() { document.getElementById('topmenu').setAttribute('style', 'display:block'); } 
 #topbar { background-color: yellow; overflow: auto; } #topmenu { display: none; } 
 <header> <div id="topbar"> <img src="/images/santorini-wedding-photographer-logo.png" style="float: left;"> <span style="float: right;"><a href="" onclick="view()">MENU</a></span> </div> <div id="topmenu"> some text here </div> </header> 

Your anchor tag has a href attribute, which is following the link and changing the page contents. 您的锚标记具有href属性,该属性位于链接之后并更改页面内容。 Remove the HREF ( which is actually a bad idea ), or better yet; 删除HREF(这实际上是一个坏主意),或者更好。 use a span or something instead. 改用跨度之类的

FYI: There are also multiple other solutions available to keep the href, but prevent the page from changing location. 仅供参考:还有许多其他解决方案可用于保留href,但可防止页面更改位置。

 function view() { document.getElementById('topmenu').setAttribute('style', 'display:block'); } 
 #topbar { background-color: yellow; overflow: auto; } #topmenu { display:none; } 
 <header> <div id="topbar"> <img src="<?php bloginfo('stylesheet_directory'); ?>/images/santorini-wedding-photographer-logo.png" style="float: left;"> <span style="float: right;"><a onclick="view()">MENU</a></span> </div> <div id="topmenu"> some text here </div> </header> 

In your anchor tag, set your href to href="#!" 在锚标记中,将href设置为href =“#!” so that the event doesn't propagate. 这样事件就不会传播。 And your code for the div to show works as expected. 您的div显示代码可以按预期工作。

It would also work with href="#", but this would take you back to the top of the page in case you're somewhere at the bottom. 它也可以与href =“#”一起使用,但是如果您位于页面底部,则可以带您回到页面顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM