2017-05-25 68 views
-1

我有几个html页面,我想添加一个eventListener只有一个html页面。添加eventListener到只有一个HTML页面?

document.addEventListener('scroll', function(e){  
// along the scroll, the img's opacity changes. 
}); 

在该html页面中,如果我滚动页面,整个页面img的opcacity更改。

的问题是,这个监听器在其他页面也将触发,

我怎么能这个监听器添加到只有一个页面?

+0

如果您在标题中包含此代码,请将其仅移至该页面。 – tech2017

+3

您可以将该函数添加到您希望加载的唯一html页面中的''标签,而不是将其放入您拥有的每个页面中导入的js文件中。 – Lixus

+0

Lixus是正确的,另一种选择是向父元素添加一个类,只有在它存在时才会触发? – atoms

回答

1

您可以使用window.location再附上事件处理程序,

if(window.location.href === 'YOUR_URL') { 
    document.addEventListener('scroll', function(e){  
    //your code 
    }); 
} 

或者你可以追加一些idbody并检查其存在。

<body id="animate-stuff"> 

if(document.getElementById('animate-stuff')) { 
    document.addEventListener('scroll', function(e){  
    //exec your code here 
    }); 
} 
+0

似乎是一个糟糕的主意,要在里面进行检查,将它放在if中并且不应用事件侦听器会更有意义。 – epascarello

+0

@epascarello oops,我的意思是,只是复制了他的代码。谢谢,会改变 –