2014-01-02 5 views
0

Я использую fancyBox 2.1.5, и у меня есть 3 селектора, которые подходят для видео и изображений по-разному. Они немного отличаются друг от друга, поэтому есть много дублированного кода.Как предотвратить дублирование кода в моей инициализации fancyBox?

Вот как это выглядит:

// Fit video content to display area, ignoring title text. 
$('.fitVideo').fancybox({ 
    helpers: { 

     // Enable the media helper to better handle video. 
     media: true, 

     // Put comments within the white border. 
     title: { 
      type: 'inside' 
     } 
    }, 

    // Do not use this because it tries to fit title text as well. 
    fitToView: false, 

    // Prevent the introduction of black bars when resized for mobile. 
    aspectRatio: true, 

    // Restrict content to the display dimensions. 
    maxWidth: "100%", 
    maxHeight: "100%", 

    // Change the title keyword to 'caption' to avoid title text in tooltips. 
    beforeLoad: function() { 
     this.title = $(this.element).attr('caption'); 
    }, 

    // Override the default iframe dimensions with manually set dimensions. 
    afterLoad: function() { 
     this.width = $(this.element).data("width"); 
     this.height = $(this.element).data("height"); 
    } 
}); 

// Fit image content to display area, ignoring title text. 
$('.fitImage').fancybox({ 
    helpers: { 

     // Put comments within the white border. 
     title: { 
      type: 'inside' 
     } 
    }, 

    // Do not use this because it tries to fit title text as well. 
    fitToView: false, 

    // Restrict content to the display dimensions. 
    maxWidth: "100%", 
    maxHeight: "100%", 

    // Change the title keyword to 'caption' to avoid title text in tooltips. 
    beforeLoad: function() { 
     this.title = $(this.element).attr('caption'); 
    } 
}); 

// Only fit image content to display width; content extends beyond the bottom of the page. 
$('.fitImageWidth').fancybox({ 
    helpers: { 

     // Put comments within the white border. 
     title: { 
      type: 'inside' 
     } 
    }, 

    // Do not use this because it tries to fit title text as well. 
    fitToView: false, 

    // Only restrict content to the display width. 
    maxWidth: "100%", 

    // Change the title keyword to 'caption' to avoid title text in tooltips. 
    beforeLoad: function() { 
     this.title = $(this.element).attr('caption'); 
    } 
}); 

Все они имеют одни и те же значения для title, type, fitToView, maxWidth и beforeLoad, так что я надеялся, что я мог бы, возможно, поместить эти свойства в $('.fancybox') догоняющий все, а затем имеют небольшие селектора с уникальными свойствами, которые «стекают» поверх этих значений по умолчанию.

Это может быть неправильный подход, хотя ... Итак, что лучший способ сделать это?

ответ

0

Выбор различных классов, как показано в моем начальном посте, на самом деле разделяет эти элементы в различных группах FancyBox, даже если все они имеют один и тот же data-fancybox-group значение.

Это означает, что вы не сможете смешивать видео и изображения в одной группе или даже изображения с различными параметрами настройки экрана, используя описанный выше подход. К счастью, это подтолкнуло меня к гораздо более элегантному решению.

$(document).ready(function() { 
    $(".fancybox").fancybox({ 

     beforeLoad: function() { 

      var elem = $(this.element); 

      if (elem.hasClass("video")) { 
       this.width = elem.data("width"); 
       this.height = elem.data("height"); 
      } 

      if (elem.hasClass("tall")) { 
       this.maxHeight = 9999; 
      } 
     } 

    }); 
}); 

Я перешел обратно выбора всех fancybox элементов (так что все может быть надлежащим образом сгруппированы), затем с помощью FancyBox beforeLoad обратного вызова, чтобы проверить, если определенный класс существует на выбранном элементе и изменение свойств соответствующим образом. До сих пор это работало!

2

Вы могли бы сделать так:

//Save your default settings 
var fancySettings = { 
    helpers: { 
     // Put comments within the white border. 
     title: { 
      type: 'inside' 
     } 
    }, 

    // Do not use this because it tries to fit title text as well. 
    fitToView: false, 

    // Only restrict content to the display width. 
    maxWidth: "100%", 

    // Change the title keyword to 'caption' to avoid title text in tooltips. 
    beforeLoad: function() { 
     this.title = $(this.element).attr('caption'); 
    } 
} 

//Apply defaults 
$('.fitImage, .fitImageWidth').fancybox(fancySettings); 
//For any modification just extend it from the new object which will override the properties if they are existing. 
$('.fitVideo').fancybox($.extend({}, fancySettings ,{helpers:{media: true}}); 
+0

Спасибо PSL, ваше предложение действительно работает, но оказалось, что весь мой подход на самом деле сломал элементы группы fancyBox. Я не уверен, что этикета StackOverflow диктует в этой ситуации, но с моим вопросом, связанным конкретно с fancyBox, я склонен опубликовать свой окончательный рабочий подход в качестве ответа. Исправьте меня, если это неправильно! – calbar

+0

@calbar Конечно, вы должны опубликовать сообщение, если считаете, что лучше подходит к вашему вопросу ... И вы можете принять его также (я думаю, через несколько часов или около того). – PSL

Смежные вопросы