Изолировать JQuery FF4 проблема - PullRequest
2 голосов
/ 12 июня 2011

В ответ другому пользователю я обновил плагин jQuery iCheckbox для работы с jQuery 1.5 и 1.6 (в Safari). Это описано в моем ответе здесь:

jquery 1.4.2, работающий на iCheckBox, а не jquery 1.6

Но по какой-то причине он не работает в FF4, и мне нужна помощь в поиске ошибки, которая влияет на FF4, в коде, найденном здесь:

http://fiddle.jshell.net/mikkelbreum/HAGMp/

Мне бы хотелось помочь, чтобы он заработал, а также некоторые общие советы о том, как отлаживать подобные вещи с помощью firebug (я не получаю никаких ошибок, вот в чем проблема, поэтому я понятия не имею, где это идет не так. Но это, вероятно, связано с анимацией или условной проверкой.)

Откройте это Safari (работает) и в FF4 (не работает, анимация не происходит): http://fiddle.jshell.net/mikkelbreum/HAGMp/show/

Я также хотел бы знать, работает ли он в IE7,8,9 или нет?

1 Ответ

2 голосов
/ 12 июня 2011

Обновление: Я посмотрел глубже на плагин, идет много дополнительной работы, вот гораздо более тонкая версия, которая делает то же самое, но выполняет меньше работы и работает в FF4 (без плагина CSS / анимации из другого ответа, указанного ниже).

Кроме того, я сделал несколько настроек - теперь вы можете нажать на изображение до завершения анимации, чтобы переключить его обратно, не нужно ждать окончания анимации, чтобы определить состояние - вместо этого мы используем состояние флажка ( что тоже сразу сказалось). API-интерфейс такой же, только внутренняя часть плагина была изменена.

/*
* iCheckbox - Inspired Checkbox v0.1
*
* Convert a checkbox or multiple checkboxes into iphone style switches.
*
* This is based on the jQuery iphoneSwitch plugin by Daniel LaBare.
*
* Features:
*    * Because checkboxes are used, this is compatable with having javascript off for form submission.
*    * Affects only checkboxes.
*    * Synchronizes the actual state of the checkbox for on or off status.
*    * Completely self-contained for each checkbox.
*    * Changes fire the onchange event of your checkbox.
*    * Relies purely on css for styling... no passing anything but your slider image.
*    * Because functionality is decoupled from CSS, you can assign custom CSS classes if you wish making it possible for multiple version per page.
*    * Completely inline like a normal checkbox. No sliding-door-float madness.
*
* iphoneSwitch Author: Daniel LaBare
*    iCheckbox Author: Bryn Mosher
*   iphoneSwitch Date: 2/4/2008
*      iCheckbox date: 2/26/2010-2/27/2010 (like most of you I'm a nite owl :P)
*/

// convert the matched element into an iCheckbox if it is a checkbox input
jQuery.fn.iCheckbox = function(start_state, options) {

    if(this.length == 0 || this[0].type != 'checkbox') return this;

    // define default settings
    var settings = jQuery.extend( {
        // switch_container_src is the outer frame image of the slider
        // you assign the actual slider image via css
        switch_container_src: 'images/iphone_switch_container.gif',
        // The height of your slider
        switch_height: 27,
        // The width of your slider
        switch_width: 94,
        // switch_speed is the speed of the slider animation.
        // Warning: Your onchange() even won't be fired until the end of this!
        switch_speed: 150,
        // How far your actual slider image has to move to change to the "off" state.
        // This can be either positive or negative based on the layout of your image.
        // The "on" state expects this image to have backgroundPosition: 0px.
        switch_swing: -53,
        // CSS class of the container if you wish.
        class_container: 'iCheckbox_container',
        // CSS class of the switch.
        // This should have your actual "on"/"off" image set as its background-image.
        class_switch: 'iCheckbox_switch',
        // CSS class of the checkbox if you wish it shown.
        class_checkbox: 'iCheckbox_checkbox',
        checkbox_hide: true,
        // animate off function
        iCheckToggle: function (elem, atime, animOnly) {
            var img = jQuery(elem).siblings('img');
            atime = typeof(atime) == 'number' ? atime : settings.switch_speed;
            img.stop(true).animate({ backgroundPositionX: (elem.checked ? '0' : settings.switch_swing) + 'px' }, {
                duraton: parseInt(atime) > 0 ? atime : 1,
                easing: 'linear',
                step: function(cur, opt){
                   img.css("background-position", opt.now + "px 0px");
                }
             });
        },
    }, options);

    // set initial state
    this.prop('checked', start_state == 'on');

    // create the switch
    return this.each(function() {
        // make the container
        var container = jQuery(this).wrap($('<span />').addClass(settings.class_container)).parent();
        // make the switch image based on starting state
        jQuery('<img class="'+settings.class_switch+'" src="'+settings.switch_container_src+'" />')
            .appendTo(container);
        // sync the checkbox to initial state
        // must have a positive time for the initial event to fire
        settings.iCheckToggle(this, 1);
        // bind clicking on the image
        jQuery(this).siblings('.'+settings.class_switch).click(function (e) {
            jQuery(this).siblings('input').click();
        }).end()
          // assign the class to it
          .addClass(settings.class_checkbox)
          // finally hide the checkbox after everything else is declared - we do this for syntax checking
          .toggle(!settings.checkbox_hide)
          // bind clicking on a visible checkbox
          .change(function (e) {
            settings.iCheckToggle(this, settings.switch_speed, true );
        });
    });
};

Вы можете проверить это здесь .


Оригинальный ответ:

Сдвиг фоновой позиции в Firefox был немного странным, свойства представлены в процентах, а не в пикселях ( попробуйте демонстрацию здесь, посмотрите предупреждение по клику в Firefox против Chrome ), поэтому анимация двигатель просто не справляется с этим правильно. Самый простой способ обойти это - подключиться к анимации / CSS-хукам, доступным в jQuery, рабочий пример этого можно увидеть в этом ответе .

Также вы захотите перейти на стандарт backgroundProperty, а не конкретно backgroundPropertyX здесь, например:

.animate({backgroundPosition: settings.switch_swing+'px 0'}, atime, 'linear')

и далее вниз:

.animate({backgroundPosition: '0 0'}, atime, 'linear')

Вот код из другого ответа в сочетании с приведенным выше в вашей демонстрации , работающий в FF4.

Примечание: вышеупомянутые изменения кода (только в этом ответе) фиксируют позицию, код в другом связанном ответе - это то, что фиксирует анимацию, чтобы добраться до этой позиции, например вот версия без анимации , если вам интересно.

...