getElementById中有多个ID [英] Multiple ID in getElementById
问题描述
我发现了一个很棒的教程,可以从页面中分离导航,以便在使用Javascript滚动时保持静态( http://code.stephenmorley.org/javascript/detachable-navigation/ )。
I've found a great tutorial to detach a navigation from the page to keep it static when you scroll using Javascript (http://code.stephenmorley.org/javascript/detachable-navigation/).
但是,我想在多个nav div上实现。
However, I'd like to implement this on more than one nav div.
另一个类名为 document.getElementById('navigation')。className
但我无法获得正确的语法
I assume it's adding another class name to document.getElementById('navigation').className
but I can't get the right syntax
这是代码:
/* Handles the page being scrolled by ensuring the navigation is always in
* view.*/
function handleScroll(){
// check that this is a relatively modern browser
if (window.XMLHttpRequest){
// determine the distance scrolled down the page
var offset = window.pageYOffset
? window.pageYOffset
: document.documentElement.scrollTop;
// set the appropriate class on the navigation
document.getElementById('navigation').className =
(offset > 104 ? 'fixed' : '');
}
}
// add the scroll event listener
if (window.addEventListener){
window.addEventListener('scroll', handleScroll, false);
}else{
window.attachEvent('onscroll', handleScroll);
}
推荐答案
code> getElementById()。该方法仅设计为获取正好一个元素(或零,如果未找到ID)。
You will have to call getElementById()
for each ID. The Method is only designed to get exactly one element (or zero, if the ID isn't found).
假设您有两个导航div,左和右,像这样:
Assuming, you have two navigation divs, left and right, like this:
<div id="navigationLeft">
<ul>
<!-- Navigation entries -->
</ul>
</div>
<!-- Maybe some content or whatever? -->
<div id="navigationRight">
<ul>
<!-- Navigation entries -->
</ul>
</div>
那么你的Javascript行将会是这样:
Then your Javascript line in question would look like this:
// set the appropriate class on the navigation
document.getElementById('navigationLeft').className = (offset > 104 ? 'fixed' : '');
document.getElementById('navigationRight').className = (offset > 104 ? 'fixed' : '');
// or, shorter but less readable (i think)
document.getElementById('navigationLeft').className
= document.getElementById('navigationRight').className
= (offset > 104 ? 'fixed' : '');
如果这还不能回答您的问题,请随意添加一些相关的HTML代码到您的题。
[更新:示例]
If this does not yet answer your question, please feel free to add some relevant HTML-Code to your question. [Update: Example]
这篇关于getElementById中有多个ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!