我正在迭代li的列表以使用此函数获取位于屏幕中心(滚动)的li:
var findMiddleElement = (function(docElm){
var viewportHeight = docElm.clientHeight,
elements = $('li');
return function(e){
var middleElement;
if( e && e.type == 'resize' )
viewportHeight = docElm.clientHeight;
elements.each(function(){
var pos = this.getBoundingClientRect().top;
// if an element is more or less in the middle of the viewport
if( pos > viewportHeight/2.5 && pos < viewportHeight/1.5 ){
middleElement = this;
return false; // stop iteration
}
});
console.log(middleElement);
}
})(document.documentElement);
到目前为止这种方法很有效。问题是'middleElement'将返回如下内容:
<li style="padding-top: 12.8438px; padding-bottom: 12.8438px;">Menu Item 8</li>
我需要为它添加CSS样式。由于middleElement.css
不起作用,我需要一种方法来获取找到的元素的选择器。
答案 0 :(得分:2)
该属性在纯JavaScript中称为“样式”。
例如:
middleElement.style.color = "red";
使用jQuery(可能性能较差):
$(middleElement).css({color:"red"})