attempting to create a script that will create a border around specific element when i hover on it
I would like to create a script that will create a border around specific element when i hover on it
the code i attempted this with..
(function(){
$(document.body).each(function(){
$(this).hover(
function(){
$(this).css('border','1px solid blue');
开发者_如何学运维},
function(){
$(this).css('border','none');
}
)
})
})()
any help will be much appreciated
Using delegate
just attach the mouseover/mouseout event to body tag instead of attaching it to all the elements on the page. Using this
we can control the css.
Note: This method is attaching only a single event handler on body element.
$(function(){
$('body').delegate("*", 'mouseover', function(e){
$(this).css('border','1px solid blue');
e.stopPropagation();
}).delegate("*", 'mouseout', function(e){
$(this).css('border','none');
e.stopPropagation();
}
);
});
Working demo
Are you attempting to give a border to every element on a page when its hovered over? If so you can try the following
Live Demo
$(function(){
$(document.body).find('*').each(function(){
$(this).hover(
function(){
$(this).css('border','1px solid blue');
},
function(){
$(this).css('border','none');
}
);
});
});
In your code you were basically saying for each body found add the hover, so the event was tied to the body.
For a specific element, say a div
with the id
of test you would do the following,
$('#test').hover(
function(){
$(this).css('border','1px solid blue');
},
function(){
$(this).css('border','none');
}
);
Heres some info on using jQuery selectors
Why use javascript to just add a hover border on one or more elements? One can use plain CSS with no programming.
You don't show what your page structure looks like or talk about exactly what you want to have the border, but if you have this HTML:
<div class="autoBorder">Some text</div>
Then, you can use this CSS to add a border upon mouse hover:
.autoBorder:hover {border: 1px solid #00F;}
// Eveything in the body
$("body *").hover(function() {
$(this).css('border', '1px solid blue');
}, function() {
$(this).css('border', 'none');
});
// Specific Element using an "id"
$("#e").hover(function() {
$(this).css('border', '1px solid red');
}, function() {
$(this).css('border', 'none');
});
// Specific elements using a "class"
$(".number").hover(function() {
$(this).css('border', '1px solid lime');
}, function() {
$(this).css('border', 'none');
});
You can find an example at: http://jsfiddle.net/Shaz/3pfRx/
精彩评论