Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

javascript - Javascript内联onclick转到本地锚点(Javascript inline onclick goto local anchor)

I have a button as an image...(我有一个按钮作为图像...)

<img src="button.png" /> I need some javascript in an onclick where when click it will navigate to a local anchor.(我在onclick中需要一些JavaScript,单击它时将导航到本地锚点。) For example:(例如:) <img src="button.png" onclick="navigateTo #page10" /> How can I do this?(我怎样才能做到这一点?) Update: This is the code I'm using:(更新:这是我正在使用的代码:) onclick="document.location=#goToPage';return false;"   ask by Satch3000 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution presented in the accepted answer has the important issue that it can only be used 1 time.(接受的答案中提出的解决方案具有一个重要问题,即只能使用1次。)

Each consecutive click appends #goToPage to location and the window won't navigate to the anchor.(每次连续单击都会将#goToPage附加到位置,并且该窗口将不会导航到锚点。) A solution is to remove the anchor part before appending a new anchor:(一种解决方案是在附加新锚之前先删除锚部分:) function goToAnchor(anchor) { var loc = document.location.toString().split('#')[0]; document.location = loc + '#' + anchor; return false; } Usage example:(用法示例:) <a href="#anchor" onclick="goToAnchor('anchor')">Anchor</a> NOTE: The anchor needs to be enclosed in quotes, without the hash prefix.(注意: 锚需要用引号引起来,而没有哈希前缀。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...