触发响应基于父元素宽度而不是窗口DOM的宽度

时间:2015-12-07 11:37:52

标签: javascript jquery twitter-bootstrap twitter-bootstrap-3 responsive-design

当我的父容器处于特定大小时,我想触发bootstrap的响应式方法,Children会相应地做出响应。

  

即如果容器是< 1200,则Children元素将转换为    MD ,而不仅仅是 LG

Fiddle Example

  1. 为名为1200
  2. 的红色边框容器调整至少#page-content-wrapper像素的小调

    enter image description here

    1. 点击Toggle Menu按钮,使#page-content-wrapper950像素被视为引导程序中的MD,表单也应转换为MD但仍保留给LG
    2. enter image description here

        
          
      1. 点击Toggle Menu按钮后,这是我的预期输出。 #page-content-wrapper小于1200,这是MD,然后是   儿童元素转变为MD。
      2.   

      enter image description here

2 个答案:

答案 0 :(得分:2)

我担心你将不得不采用javascript方式。媒体查询无法知道元素的维度。

设置切换时,您可以使用javascript / jquery删除某些类,具体取决于新元素宽度是小于还是大于断点。

然而,这样做会使您失去媒体查询功能,因此在调整窗口大小时,它将不再响应。您也可以通过收听onresize事件来规避这一点。

这就是我提出的:

小提琴: https://jsfiddle.net/mq1b8qyd/8/

请注意,我已将.respond-parent类添加到需要响应其父级大小的元素中。

它也不是最干净的解决方案,但在您提供的示例中,它可以正常工作。如果事情变得更复杂,那么根据所需的宽度,您需要不同的类.respond-parent

<强>的Javascript

/* Latest compiled and minified JavaScript included as External Resource */

$("#menu-toggle").click(function(e) {
  e.preventDefault();
  $("#wrapper").toggleClass("toggled");
});

function checkWidth() {
  var wrapperWidth = $('#page-content-wrapper').outerWidth();
  var $responsiveParent = $('.respond-parent');
  $("#page-content-wrapper h2").text("The width for the #page-content-wrapper is " + wrapperWidth);

  alert('checking width: ' + wrapperWidth);
  if (wrapperWidth >= 1200) {
    $responsiveParent.attr('class', 'respond-parent col-lg-12');
  } else if (wrapperWidth >= 992) {
    $responsiveParent.attr('class', 'respond-parent col-md-8');
  } else if (wrapperWidth >= 768) {
    $responsiveParent.attr('class', 'respond-parent col-sm-6');
  } else {
    $('.respond-parent').attr('class', 'respond-parent col-xs-12');
  }
}

$(document).ready(function() {
  var wrap = $("#page-content-wrapper").outerWidth();

  $(window).resize(checkWidth);
  $('#wrapper').bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', checkWidth);
});

答案 1 :(得分:0)

立即尝试

https://jsfiddle.net/mq1b8qyd/9/

我删除了position: absolute;上的#page-content-wrapper 并删除了侧边栏的toggled类,因此最初侧边栏应隐藏

相关问题