Using jQuery to set the CSS of an element using one of that elements own CSS properties?
I am trying to add a standard style to all javascript scripted hyperlinks in my webapps. Replacing the standard solid line with a dotted line. This can be achieved with CSS however there is a major drawback to that, the border color doesn't match the link color. I figured since the links are using JS anyways, why not do it with JS. Here is what I'm trying to do in jQuery.
$(function(){
$('a.scripted').css({
'text-decoration': 'none',
'border-bottom': '1px dotted',
'border-color': $(this).css('color'),
});
});
However, this doesn't work. $(this) doesn't refer to the selected element and that makes sense. My question is, how can I do this? I tried wrapping it like this:
$(function(){
$('a.scripted').ready(function(){
$(this).css({
'text-decoration': 'none',
'border-bottom': '1px dotted',
'border-color': $(this).css('color'),
});
});
});
This also did not work. Advice?
EDIT
This code works but not for visi开发者_Go百科ted links. I know about the jQuery selector :visited
but how do I use that in this context?
$(function(){
$('a.scripted').each(function(){
var $this = $(this);
$this.css({
'text-decoration': 'none',
'border-bottom': '2px dotted',
'border-color': $this.css('color'),
});
$this.hover(
function()
{
$this.css({
'text-decoration': 'none',
'border-bottom': '1px dotted',
'border-color': $this.css('color'),
});
},
function()
{
$this.css({
'text-decoration': 'none',
'border-bottom': '1px dotted',
'border-color': $this.css('color'),
});
}
);
$this.click(function(){
$this.css({
'text-decoration': 'none',
'border-bottom': '1px dotted',
'border-color': $this.css('color'),
});
});
});
});
You could use each, then $(this) inside to give you a reference to the element being iterated over.
$(function(){
$('a.scripted').each( function() {
var $this = $(this);
$this.css({
'text-decoration': 'none',
'border-bottom': '1px dotted',
'border-color': $this.css('color')
});
});
});
I would use the each method.
$('a.scripted').each(function () {
$(this).css({
'text-decoration': 'none',
'border-bottom': '1px dotted',
'border-color': $(this).css('color'),
});
});
$(function(){
$('a.scripted').css({
'text-decoration': 'none',
'border-bottom': '1px dotted ',
});
});
Check working example at http://jsfiddle.net/qERuL/5/
You really ought to do it with css, if at all possible. Wherever you set your link colors, also set the bottom color of scripted links. If you have multiple places where these links could appear (with different colors for each place), write an a.scripted
block for each of them.
a {
color: blue; /* or whatever color you like */
}
a.scripted {
text-decoration: none;
border-bottom: 1px dotted;
border-color: blue; /* same as above */
}
精彩评论