开发者

Toggling background image (jQuery)

开发者 https://www.devze.com 2023-01-04 09:16 出处:网络
$(\'textarea\').focus(function() { var img = $(this).css(\'background-image\'); $(thi开发者_如何学Cs).css(\'background-image\', \'none\');
$('textarea').focus(function() {
    var img = $(this).css('background-image');
    $(thi开发者_如何学Cs).css('background-image', 'none');
});
$('textarea').blur(function() {
    $(this).css('background-image', img);
});

.. doesn't seem to work. I think somethings wrong, but I can't figure out what.

Many thanks for your help!


If you define

var img

just inside the .focus() event handler, that variable will not be available within .blur()

So either define var img globaly, or use jQuerys .data() method for instance.

write:

$.data(this, 'img', $(this).css('background-image'));

read:

$.data(this, 'img');

example:

$('textarea').focus(function() {
   var $this = $(this);
   $.data(this, 'img', $this.css('background-image'));
   $this.css('background-image', 'none');
});
$('textarea').blur(function() {
   $(this).css('background-image', $.data(this, 'img') || '');
});


Try to define the url-address for the image in css.

var img = 'images/mybg.png';
$('textarea').blur(function() {
    $(this).css('background-image', 'url('+img+')');
});
0

精彩评论

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

关注公众号