问题
I'm using Bootstrap's Carousel to create a dashboard that shows a bunch of Highcharts widgets. I've successfully implemented it so 1 chart shows up and used a bit of "chunking" logic to show 2 widgets at a time. This all works great, but I'd like to enhance things:
- If the user has a screen size big enough to fit 2 charts, show 2 charts and paginate by 2.
- If the user has a small screen size that only fits 1 chart, show 1 and paginate by 1.
- If the user has a screen size < 2 up, but > 1, show 1.5 charts and paginate by 1.
I'm using AngularJS to build the HTML. It's easy enough to do #1 and #2 in separate template blocks and then show/hide based on screen size. However, I'm a bit stumped on #3. I can't figure out how to display 2 charts, but only paginate by 1.
回答1:
I ended up writing the following JavaScript to do this. Basically, I'm rendering two different sections (with classes .oneup and .twoup) and then adding a "preview" if .oneup is displayed.
<script type="text/javascript">
var chartBar = $('#chart-bar');
function chartPreview(firstChart) {
var chartBarWidth = chartBar.width();
if (chartBarWidth > 600) {
var currentChart = $('.carousel-inner:visible .active');
// append the next widget to the current item
var chartToCheck = (firstChart) ? currentChart : currentChart.next();
if (chartToCheck.next()) {
chartToCheck.next().find('.widget').clone().appendTo(chartToCheck);
$('.carousel-inner').css({'margin-left': '10px', 'width': '98.8%'})
}
} else if (chartBarWidth > 1040) {
$('.carousel-inner').css({'margin-left': '0', 'width': '100%'})
}
}
$(document).ready(function() {
$('.widgets').sortable({
cursor: "move",
handle: ".heading"
}).disableSelection();
$('.boxes,.tasks').sortable();
var carousel = $('.carousel');
$(carousel).carousel({
interval: 0
});
if (chartBar.width() < 1040) {
chartBar.find('.oneup').show();
chartPreview(true);
carousel.bind('slide', function() {
chartPreview(false);
});
} else {
chartBar.find('.twoup').show();
}
});
It'd be nice if I didn't have to render both oneup and twoup, but I'm not sure how to do that with AngularJS. Here's my oneup ng-repeat:
<div class="carousel-inner">
<div class="item chart"
ng-repeat="widget in widgets | filter: {type: 'chart'} | orderBy: 'order'"
ng-class="{active: $index == 0}">
<chart class="widget" value="{{widget}}" type="{{widget.chartType}}"></chart>
</div>
</div>
Versus the twoup ng-repeat:
<div class="carousel-inner">
<div class="item chart"
ng-repeat="widget in widgets | filter: {type: 'chart'} | chunk: 2 | orderBy: 'order'"
ng-class="{active: $index == 0}">
<chart class="widget" value="{{widget[0]}}" type="{{widget[0].chartType}}"></chart>
<chart class="widget" value="{{widget[1]}}" type="{{widget[1].chartType}}"></chart>
</div>
</div>
来源:https://stackoverflow.com/questions/14858011/bootstrap-carousel-that-shows-different-number-of-items-based-on-screen-size