繁体   English   中英

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

[英]Trigger Responsiveness based on Parent's element Width not on Window DOM's width

当父容器的大小达到一定大小时,我想触发引导程序的响应方法,子进程将做出相应响应。

例如,如果container < 1200 ,则子元素将转换为MD而不是仅保留到LG

小提琴的例子

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

在此处输入图片说明

  1. 单击“ Toggle Menu按钮,该按钮将#page-content-wrapper设置为950像素(被视为引导程序中的MD),表格也应转换为MD,但仍保留为LG

在此处输入图片说明

  1. 单击“ Toggle Menu按钮后,这是我的预期输出。 #page-content-wrapper小于1200,即为MD,然后,Children元素转换为MD。

在此处输入图片说明

恐怕您将不得不使用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);
});

立即尝试

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM