0

我想根据范围/滑块的值更改 ui-slider-handle 的 background-image:url (JQuery Mobile)

大致像http://jsfiddle.net/phillpafford/YgJ9P/2/但是,正如我所说,我希望看到滑块手柄的背景图像发生变化。

$("#slider").change(function() {
    sVal = $(this).val();

    if(sVal > 21 && sVal <= 40) {
        $('#theImage').attr('src', 'http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/21-skull.png');
    }

    if(sVal > 41 && sVal <= 60) {
        $('#theImage').attr('src', 'http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/18-envelope.png');
    }

    if(sVal > 61 && sVal <= 80) {
        $('#theImage').attr('src', 'http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/100-coffee.png');
    }

    if(sVal > 81 && sVal <= 100) {
        $('#theImage').attr('src', 'http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/88-beermug.png');
    }

});​
4

1 回答 1

1

您只需要选择句柄元素而不是 Phill 在他的 JSFiddle 中选择的那个:

$("#slider").change(function() {
   var sVal = $(this).val(),
       $ele = $(this).next().children();

    if(sVal > 21 && sVal <= 40) {
        $ele.addClass('skull-class').removeClass('envelope-class coffee-class beermug-class');
    }

    if(sVal > 41 && sVal <= 60) {
        $ele.addClass('envelope-class').removeClass('skull-class coffee-class beermug-class');
    }

    if(sVal > 61 && sVal <= 80) {
        $ele.addClass('coffee-class').removeClass('envelope-class skull-class beermug-class');
    }

    if(sVal > 81 && sVal <= 100) {
        $ele.addClass('beermug-class').removeClass('envelope-class coffee-class skull-class');
    }

});​

这是一个演示:http: //jsfiddle.net/jasper/YgJ9P/192/

我没有使用.css()给元素添加样式,而是设置了一些类来保持我的 JS 代码和我的 CSS 代码分开:

.ui-slider .skull-class {
    background : url(http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/21-skull.png);
}
.ui-slider .envelope-class {
    background : url(http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/18-envelope.png);
}
.ui-slider .coffee-class {
    background : url(http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/100-coffee.png);
}
.ui-slider .beermug-class {
    background : url(http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/88-beermug.png);
}​

你也可以稍微压缩一下JS:

var allClasses = 'skull-class envelope-class coffee-class beermug-class';
$("#slider").change(function() {

    //get the value of the slider as well as cache the slider handle element
    var sVal = $(this).val(),
        $ele = $(this).next().children();

    //remove the icon classes from the handle
    $ele.removeClass(allClasses);

    (sVal > 21 && sVal <= 40) ? $ele.addClass('skull-class') :
        (sVal > 41 && sVal <= 60) ? $ele.addClass('envelope-class') :
            (sVal > 61 && sVal <= 80) ? $ele.addClass('coffee-class') : 
                (sVal > 81 && sVal <= 100) ? $ele.addClass('beermug-class') : ''
});​

http://jsfiddle.net/jasper/YgJ9P/195/

于 2012-07-10T15:48:21.240 回答