切换背景图像(jQuery)

3zz*_*zzy 0 jquery textarea background toggle

$('textarea').focus(function() {
    var img = $(this).css('background-image');
    $(this).css('background-image', 'none');
});
$('textarea').blur(function() {
    $(this).css('background-image', img);
});
Run Code Online (Sandbox Code Playgroud)

..似乎没有用.我觉得有些不对劲,但我无法弄清楚是什么.

非常感谢您的帮助!

jAn*_*ndy 7

如果你定义

var img
Run Code Online (Sandbox Code Playgroud)

就在.focus()事件处理程序内部,该变量将不可用 .blur()

所以要么定义var imgglobaly,要么使用jQuerys .data()方法.

写:

$.data(this, 'img', $(this).css('background-image'));
Run Code Online (Sandbox Code Playgroud)

读:

$.data(this, 'img');
Run Code Online (Sandbox Code Playgroud)

例:

$('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') || '');
});
Run Code Online (Sandbox Code Playgroud)