开发者

Create new div arround anchor link when clicked

开发者 https://www.devze.com 2022-12-23 18:43 出处:网络
How can I achieve this behaviors onclick with jquery : default state: <a href=\"something.html\">Anchor</a>

How can I achieve this behaviors onclick with jquery :

default state:

<a href="something.html">Anchor</a>

click state

<div class="highlight">
<a href="something.html">Anchor</a>
</div>开发者_高级运维


Well, you can use the jQuery "wrap" function:

$('#idOfAnchor').click(function(a) {
  $(a).wrap($('<div/>').addClass('highlight'));
});

That seems like kind-of a funny idea however. Why not just add the class directly to the <a> element itself?

Oh sorry - your question says "clicked" but the explanation says "hover". That's going to be a little trickier, because you're going to want to get rid of that extra div when you mouse out. Again, if this were my page, I just wouldn't do that at all. What is it that you're trying to achieve?

edit again: ok now it says "click" again :-)


Fastest way to do this:

$('a').click(function() {
  $(this).wrap($('<div/>', { 'class': 'highlight'}));
});

However, this is probably what you want, much simpler just use whatever CSS effect you want:

$('a').click(function() {
  $(this).addClass('highlight'});
});


Checkout jQuery's wrap function.

$(this).wrap('<div class="highlight"></div>');


Why don't you just style a:hover?

Something like this in CSS:

.highlight a {
    /* style */
}

.highlight a:hover {
    /* hover style */
}

Then change your HTML to:

<a href="something.html" class='highlight'>Anchor</a>
0

精彩评论

暂无评论...
验证码 换一张
取 消