我正在使用FlexSlider创建一个响应库,使用来自本站的一些指令。我只是想知道是否有一种方法可以使用断点来设置变量(1,2,3等),而不是重复一堆代码。与断点一起更改的唯一设置是“minItems”和“maxItems”,再次设置所有设置似乎很愚蠢。因此,基本上只是试图清理JavaScript,使其更加简洁。
FlexSlider:http://www.woothemes.com/flexslider/
<div class="flexslider-container">
<div class="flexslider">
<ul class="slides">
<li>
<img src="image1.jpg" />
</li>
<li>
<img src="image2.jpg" />
</li>
<li>
<img src="image3.jpg" />
</li>
<li>
<img src="image4.jpg" />
</li>
</ul>
</div>
</div>CSS
/* breakpoint_1 */
body:after { display: none; content: 'breakpoint_1'; }
.flexslider { max-width: 1080px; margin : 0 auto; }
/* breakpoint_2 */
@media all and (min-width: 480px) {
body:after { display: none; content: 'breakpoint_2'; }
}
/* breakpoint_3 */
@media all and (min-width: 720px) {
body:after { display: none; content: 'breakpoint_3'; }
}JavaScript
$(document).ready(function(){
var currentBreakpoint;
var didResize = true;
var raw_slider = $(".flexslider").html();
$(window).resize(function() {
didResize = true;
});
setInterval(function() {
if(didResize) {
didResize = false;
var newBreakpoint = window.getComputedStyle(document.body, ':after').getPropertyValue('content');
newBreakpoint = newBreakpoint.replace(/"/g, "");
newBreakpoint = newBreakpoint.replace(/'/g, "");
if (currentBreakpoint != newBreakpoint) {
$(".flexslider").remove();
$(".flexslider-container").append("<div class='flexslider'></div>");
$(".flexslider").html(raw_slider);
if (newBreakpoint === 'breakpoint_1') {
currentBreakpoint = 'breakpoint_1';
$(".flexslider").flexslider({
animation: "slide",
animationLoop: false,
itemWidth: 360,
itemMargin: 0,
minItems: 1,
maxItems: 1,
controlNav: false
});
}
if (newBreakpoint === 'breakpoint_2') {
currentBreakpoint = 'breakpoint_2';
$(".flexslider").flexslider({
animation: "slide",
animationLoop: false,
itemWidth: 360,
itemMargin: 0,
minItems: 2,
maxItems: 2,
controlNav: false
});
}
if (newBreakpoint === 'breakpoint_3') {
currentBreakpoint = 'breakpoint_3';
$(".flexslider").flexslider({
animation: "slide",
animationLoop: false,
itemWidth: 360,
itemMargin: 0,
minItems: 3,
maxItems: 3,
controlNav: false
});
}
}
}
}, 250);
});发布于 2022-06-29 08:16:31
您可以使用一个函数作为minItems和maxItems的值,就像这个例子那样。代码:
(function() {
// store the slider in a local variable
var $window = $(window),
flexslider = { vars:{} };
// tiny helper function to add breakpoints
function getGridSize() {
return (window.innerWidth < 600) ? 2 :
(window.innerWidth < 900) ? 3 : 4;
}
$(function() {
SyntaxHighlighter.all();
});
$window.load(function() {
$('.flexslider').flexslider({
animation: "slide",
animationLoop: false,
itemWidth: 210,
itemMargin: 5,
minItems: getGridSize(), // use function to pull in initial value
maxItems: getGridSize() // use function to pull in initial value
});
});
// check grid size on resize event
$window.resize(function() {
var gridSize = getGridSize();
flexslider.vars.minItems = gridSize;
flexslider.vars.maxItems = gridSize;
});
}());https://stackoverflow.com/questions/20235509
复制相似问题