代码之家  ›  专栏  ›  技术社区  ›  eozzy

如果文本区域中存在内容,则清除背景(jQuery)

  •  1
  • eozzy  · 技术社区  · 15 年前

    请看这个jsFiddle: https://jsfiddle.net/Wmq6f/

    $('textarea').focus(function() {
       var $this = $(this);
       $.data(this, 'img', $this.css('background-image'));
       $this.css('background-image', 'none');
    });
    $('textarea').blur(function() {
        if($.trim($('textarea').val()).length){
             $this.css('background-image', 'none');
        } else {
            $(this).css('background-image', $.data(this, 'img'));
        }
    });
    

    谢谢你的帮助

    2 回复  |  直到 4 年前
        1
  •  3
  •   Syscall - leaving SO... Juhzuri    4 年前

    textarea

    另外,从中找出逻辑也可能有帮助 focus blur 回调到一个单独的函数中,因为两个事件都需要进行相同的检查。

    1. 如果textarea为空,则显示图像
    2. 否则隐藏图像

    在一个单独的函数中分解这个逻辑的另一个优点是,您可以调用onload这个新函数,它将在任何焦点或模糊事件发生之前初始化textarea。

    在jsfiddle上,当您选择 "onLoad" 选项,JavaScript代码自动包装在window.load回调中,因此您不必在代码中指定它。要么这样要么选择 "No wrap" 选项在代码中自己编写window.load事件。

    Fiddle update :

    function init(text) {
        text = $(text);
        text.data('img', text.css('background'));
        
        var update = function() {
            if(text.val() == '') {
                text.css('background', text.data('img'));
            }
            else {
                text.css('background', 'none');
            }
        };
    
        text.focus(update);
        text.blur(update);
    
        update();
    }
    
    init('textarea');
    
    ​
    
        2
  •  -1
  •   Syscall - leaving SO... Juhzuri    4 年前
    $('textarea').focus(function() {
       var $this = $(this);
       $.data(this, 'img', $this.css('background-image'));
       $this.css('background-image', 'none');
    });
    $('textarea').blur(function() {
        var $this = $(this); // you forgot this line...
        if($.trim($($this).val()).length){
             //       ^----- do not use 'textarea'
             $this.css('background-image', 'none');
        } else {
            $(this).css('background-image', $.data(this, 'img'));
        }
    });
    

    updated working version of your link

    编辑:

    css格式

    #mytextarea {
        width:300px;
        height:200px;
        border:1px solid #000;
        
    }
    .bg {
        background:url('http://img821.imageshack.us/img821/2853/writeus.gif') center no-repeat;
    }
    

    html格式

    <textarea id="mytextarea" class="bg">help!</textarea>​
    

    $('textarea').focus(function() {
        $(this).removeClass('bg');
    });
    $('textarea').blur(function() {
        var $this = $(this);
        if($.trim($this.val()).length && $.trim($this.val()) != this.defaultValue ){
            $(this).removeClass('bg');
        } else {
            $(this).addClass('bg');
        }
    });
    

    udated version of demo