Hover using javascript
Here's what I would like to do. I have 2 identical lists that I would like to have change color on hover of a specific item on both lists simultaneously.
Example:
L开发者_C百科ist One
List Item 1 List Item 2 List Item 3List Two
List Item 1 List Item 2 List Item 3So if you were to hover over List One's first item it would highlight List Two's first item also.
Any help on this would save my life thanks very much. V
Sample code:
<style>
.active { color: red; font-weight: bold; }
</style>
<body>
<ul id="list1">
<li>foo</li>
<li>bar</li>
</ul>
<ul id="list2">
<li>foo</li>
<li>bar</li>
</ul>
<script>
(function() {
var list1 = document.getElementById('list1'),
list2 = document.getElementById('list2');
function setActive(target, b) {
if(!target.tagName.toLowerCase() === 'li') return;
// determine position in list:
for(var i = 0; target = target.previousSibling; ++i);
list1.childNodes[i].className = b ? 'active' : '';
list2.childNodes[i].className = b ? 'active' : '';
}
// mouseover/mouseout are bubbling, so add the listeners to parents:
list1.onmouseover = list2.onmouseover = function(event) {
setActive((event && event.target) || window.event.srcElement, true);
};
list1.onmouseout = list2.onmouseout = function(event) {
setActive((event && event.target) || window.event.srcElement, false);
};
})();
</script>
Just off the top of my head, you could use jquery to select a specific tag in each list and apply a style to it. Maybe use the .addClass method to add a css style to the same items in the array of tags for both select lists.
HTML
<ul id="list1">
<li>item 1</li>
<li>item 2</li>
</ul>
<ul id="list2">
<li>item 1</li>
<li>item 2</li>
</ul>
jQuery
$("#list1 li").hover(
function(){
var ind = $("#list1 li").index($(this));
$("#list2 li:eq(" + ind + ")").addClass("highlight");
$(this).addClass("highlight");
},
function(){
var ind = $("#list1 li").index($(this));
$("#list2 li:eq(" + ind + ")").removeClass("highlight");
$(this).removeClass("highlight");
}
);
The highlight class will have the style that you wish to apply to both lists.
精彩评论