用jquery删除span

时间:2014-04-02 03:55:43

标签: javascript jquery html css mobile

我正在尝试使用jquery删除带有类的span。我的目标是在屏幕小于480px时移除此范围。我已经尝试过.remove();但是当屏幕低于480px时,它不会移除跨度。

我正在使用CSS /媒体查询来控制和自定义页面。

这是我的小提琴FIDDLE EXAMPLE

HTML

<span class="textbox">This is what we made of you!</span>

CSS

@media screen and (max-width: 368px) {
    .container{width: 368px;     margin: 0 auto;
    padding: 0; display: block;}

     span .textbox{display: none;}

    .nav{display: none;}

    .header{width: 368px;}
}

JQUERY

$(document).ready(function () {
     var words = [
                    'Special', 'Dynamic', 'Simple', 'Great', 'Better',
                    'Stronger', 'Stylish', 'Flawless', 'Envied',
                    'Strong', 'Sucessful', 'Grow', 'Innovate', 'Global',
                    'Knowledgable', 'Unique', 'Trusted', 'Efficient',
                    'Reliable', 'Stable', 'Secure', 'Sofisticated',
                    'Evolving', 'Colorful', 'Admirable', 'Sexy', 'Trending',
                    'Shine', 'Noted', 'Famous', 'Inspiring', 'Important',
                    'Bigger', 'Stylish', 'Expand', 'Proud', 'Awesome',
                    'Solid'
                    ], i = 0;
        var getRandomWord = function () {
        return words[Math.floor(Math.random() * words.length)];
        };

    setInterval(function(){
        $('.textbox').fadeOut(500, function(){
        $(this).html(getRandomWord()).fadeIn(500);
    });
    }, 5000);

});

3 个答案:

答案 0 :(得分:2)

span .textbox{display: none;}

应该是:

span.textbox{display: none;}

因为您的原始代码会选择具有textbox类且具有span父级的所有元素,而不是具有textbox类的实际span元素。


更新

我没有发现你正在使用fadeIn,它实际上会覆盖你的display: none属性。最快的修复(无需检查JS中的窗口宽度以及所有......)是为不透明度设置动画而不是使用淡入淡出,因为这不会改变元素的显示状态,并且CSS规则将保持活动状态。 / p>

所以,你的间隔函数应该是:

setInterval(function(){
    $('.textbox').animate({'opacity': 0}, 500, function(){
        $(this).html(getRandomWord()).animate({'opacity': 1}, 500);
    });
}, 3000);

在此处查看此行动:http://jsfiddle.net/9B7vz/3/

答案 1 :(得分:2)

当宽度减小到480px以下时,你当前的CSS确实会隐藏文本,但是jQuery fadeIn函数会将其恢复到视图中,因为fadeIn会改变该元素的显示属性。

答案 2 :(得分:0)

尝试

@media screen and (max-width: 480px) {
    .textbox {
        display: none;
    }
}

然后

var interval;
function handler() {
    var width = $(window).width();
    //if window size is > 480 and there is no interval set then create a new interval
    if (width >= 480 && !interval) {
        interval = setInterval(function () {
            $('.textbox').fadeOut(500, function () {
                $(this).html(getRandomWord()).fadeIn(500);
            });
        }, 5000);
    } else if (width < 480 && interval) {
        //if window width < 480 and there is a interval clear it and hide the textbox
        clearInterval(interval);
        interval = undefined;
        $('.textbox').hide();
    }
}
handler();
//to handle resizing of window
$(window).resize(handler);

演示:Fiddle