Подтвердить что ты не робот

Как я могу настроить код css, основанный на загрузке, так что он более чувствителен к ширине страницы?

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

введите описание изображения здесь

Я думал о том, чтобы сделать это более восприимчивым, добавив мобильные запросы CSS, но затем в коде, который у меня есть:

@media (max-width: 545px) {


.outer{
  width:100%;
  height:330px;
  top:0;
  position:relative;
}

.inner1{
  width:100%;
  height:320px;
  margin-bottom:0px;

}
.inner2{
  width:100%;
  height:330px;
  margin-bottom:0px;

}
}

@media (max-width: 435px) {

.outer{
  width:100%;
  height:380px;
  top:0;
  position:relative;
}

.inner1{
  width:100%;
  height:370px;
  margin-bottom:0px;

}
.inner2{
  width:100%;
  height:380px;
  margin-bottom:0px;

}

}

@media (max-width: 378px) {

 .outer{
  width:100%;
  height:460px;
  top:0;
  position:relative;
}

.inner1{
  width:100%;
  height:450px;
  margin-bottom:0px;

}
.inner2{
  width:100%;
  height:460px;
  margin-bottom:0px;

}

} 

и т.д., поэтому множество значений для разных ширины экрана. Я подозреваю, что есть другой способ сделать это, самый отзывчивый способ, которым мне не нужно покрывать каждую ширину экрана отдельно в мобильном CSS... Можете ли вы дать мне подсказку, как я могу изменить свой код, чтобы он работал независимо на любой ширине устройства/экрана? Спасибо!

4b9b3361

Ответ 1

Задайте минимальную ширину и высоту для каждого класса, чтобы страница перестала корректировать текст с слишком малыми разрешениями экрана. Добавить min-height: 123px; и минимальная ширина: 456 пикселей; (при необходимости отрегулируйте px), чтобы они не перекрывались на небольших экранах.

Примечание. Это не очень удобно для мобильных устройств.

Ответ 2

В вашей скрипке вы устанавливаете высоту каждого div (inner1 и inner2), а когда вы сжимаете ширину страницы до 150 пикселей (изображение), divs переполняются. Установка высоты элементов выполняется не часто, по крайней мере, из моего опыта. На мобильных платформах ширина обычно больше беспокоит.

Настройка атрибута переполнения внутри вашего css для каждого div исправила проблему для меня.

.inner1{
  width:100%;
  height:270px;
  margin-bottom:0px;
overflow: auto;
}
.inner2{
  width:100%;
  height:280px;
  margin-bottom:0px;
  overflow: auto;
}

Ответ 3

Проблема, с которой вы столкнулись, вызвана тем, что содержимое .inner1 становится слишком высоким и отображается в вашем .inner2..inner1 может стать слишком высоким из-за их переполнения. Он показывает ваш текст даже за указанную вами высоту. Чтобы остановить это поведение, примените

.inner1{
overflow:hidden;  
}

Тем не менее, я не могу рекомендовать использовать метод, который вы использовали для того, чтобы содержимое отображалось/исчезало (с фиксированной высотой). Я бы лично использовал display: none и remove display: none в коде (и возможной анимации) в этом сценарии. Но это выходит за рамки заданного вопроса, поэтому я не буду вникать в это.

JSFiddle

HTML (с загрузкой)

<div class= "container">
                <div class="row">
                    <div class="col-sm-7 company">
                        <h2>this is my title</h2>
                        <div class="companyDescription" >
                            <div class="outer">
                                <div class="inner1" id="inner1">
                                <h5>"The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet
                                    </h5><h5>Some kind of subtitle</h5>
                                    <h5><a id="readMore" style="cursor: pointer; cursor: hand;">read more...</a></h5>
                                </div>
                                <div class="inner2">
                                    <h5><a id="readLess" style="cursor: pointer; cursor: hand;">...read less</a></h5>
                                    <h5>As the use of typewriters grew in the late 19th century, the phrase began appearing in typing and stenography lesson books as a practice sentence. Early examples of publications which used the phrase include Illustrative Shorthand by Linda Bronson (1888), How to Become Expert in Typewriting: A Complete Instructor Designed Especially for the Remington Typewriter (1890)
                                    </h5>
                                    <h5>the last subtitle.</h5>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>
                    </div>

CSS

  .company {
  padding-top: 160px;
  color: #000;
}

.companyDescription {
  margin: 20px 0 10px 0;
  overflow:hidden;
}

.outer{
  width:100%;
  height:280px;
  top:0;
  position:relative;
}

.inner1{
  width:100%;
  height:270px;
  margin-bottom:0px;
  overflow:hidden;/*ONLY ONE NEW CSS LINE!*/
}
.inner2{
  width:100%;
  height:280px;
  margin-bottom:0px;
}

Javascript (с jQuery)

$('#readMore').click(function(){
    $('.companyDescription').animate({
        scrollTop:$('#inner1').outerHeight()+30
    }, 1000);
})
$('#readLess').click(function(){
    $('.companyDescription').animate({
        scrollTop:0
    }, 1000);
})

Ответ 4

Вот мой код, который вы также можете пройти через ссылку -

JSFiddle

Код HTML -

<div class="col-md-12">
  <div class="row">
    <div class="col-md-12 company">
      <h2>this is my title</h2>
      <div class="companyDescription">
        <div class="outer">
          <div class="inner1" id="inner1">
            <h5>"The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet
                                        </h5>
            <h5>Some kind of subtitle</h5>
            <h5><a id="readMore" style="cursor: pointer; cursor: hand;">read more...</a></h5>
          </div>
          <div class="inner2">
            <h5 style="display:none;"><a id="readLess" style="cursor: pointer; cursor: hand;">...read less</a></h5>
            <h5 style="display:none;">As the use of typewriters grew in the late 19th century, the phrase began appearing in typing and stenography lesson books as a practice sentence. Early examples of publications which used the phrase include Illustrative Shorthand by Linda Bronson (1888), How to Become Expert in Typewriting: A Complete Instructor Designed Especially for the Remington Typewriter (1890)
                                        </h5>
            <h5 style="display:none;">the last subtitle.</h5>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Код JAVASCRIPT -

$('#readMore').click(function() {
    $('#readMore').css('display','none');
  $('.inner2').find('h5').css('display','block');
})
$('#readLess').click(function() {
$('#readMore').css('display','block');
  $('.inner2').find('h5').css('display','none');
})

Ответ 5

Bootstrap уже обеспечивает лучший отзывчивый дизайн. Но если вы хотите добавить более отзывчивость, вы можете добавить свои собственные классы с помощью тегов html, а затем использовать медиа-запросы для определенной ширины.

<div class="container class1">
    content here
</div>

<ul class="list-item class2">
  <li> list item </li>
</ul>

теперь вы должны применить свой css к вашим заданным классам, которые в этом случае class1 и class2

Спасибо

Ответ 6

У нас есть 2 варианта,

1. Установите большую статическую высоту...

Измените статически установленную ширину на большое число, например, скажем 250px, который будет хорошо работать для низкого разрешения... но будет иметь слишком много (уродливого) пробела на рабочем столе.

.inner1{
  width:100%;
  height:250px;
  margin-bottom:0px;
  overflow: auto;
}
.inner2{
  width:100%;
  height:250px;
  margin-bottom:0px;
  overflow: auto;
}

2. Динамически вычислять высоту на resize...

Эта работа работает для всех разрешений с одинаковым количеством пробелов по желанию во всех разрешениях;) Для этого

Сначала оберните содержимое в .inner1 и .inner2 в контейнере, мы использовали article здесь... это поможет нам определить высоту содержимого.

Теперь установите высоту на 100% для .inner1 и .inner2...

.inner1 {
  width: 100%;
  height: 100%; /* Set height as 100% */
  margin-bottom: 0px;
}
.inner2 {
  width: 100%;
  height: 100%; /* Set height as 100% */
  margin-bottom: 0px;
}

Затем дайте .outer значение по умолчанию, например, 160px

.outer {
  width: 100%;
  height: 160px;
  top: 0;
  position: relative;
}

Наконец, некоторые JS, чтобы заставить его работать;)

Обновление
Мы используем функцию, назначаемую var, вместо использования анонимной функции.

В окне изменения размера мы проверяем высоту содержимого внутри inner1 и inner2, используйте тот, у кого больше контента, используя Math.max, затем добавьте к нему 25px желоба и установите его как .outer height...

  var fixWidths = function() {
    var
      $cDesc = $('.companyDescription');
    $cDesc.find('.outer').css(
      'height',
      Math.max(
        $cDesc.find('.inner1').children('article').outerHeight(),
        $cDesc.find('.inner2').children('article').outerHeight()
      ) + 25 // Maximum of the two
    )
  }

  $(window).resize(fixWidths);
  fixWidths();

Обновление
Убедитесь, что ваш JS-код завернут в...

$(function() {
  ...
});

Это будет ждать загрузки документа doc.

В конце мы вызываем программное изменение размера, чтобы установить правильное начальное состояние.

Рабочий пример

$(function() {
  $('#readMore').click(function() {
    $('.companyDescription').animate({
      scrollTop: $('#inner1').outerHeight() + 30
    }, 1000);
  })
  $('#readLess').click(function() {
    $('.companyDescription').animate({
      scrollTop: 0
    }, 1000);
  })

  var fixWidths = function() {
    var
      $cDesc = $('.companyDescription');
    $cDesc.find('.outer').css(
      'height',
      Math.max(
        $cDesc.find('.inner1').children('article').outerHeight(),
        $cDesc.find('.inner2').children('article').outerHeight()
      ) + 25 // Maximum of the two
    )
  }

  $(window).resize(fixWidths);
  fixWidths();
});
.company {
  padding-top: 160px;
  color: #000;
}
.companyDescription {
  margin: 20px 0 10px 0;
  overflow: hidden;
}
.outer {
  width: 100%;
  height: 160px;
  top: 0;
  position: relative;
}
.inner1 {
  width: 100%;
  height: 100%;
  /* Set height as 100% */
  margin-bottom: 0px;
}
.inner2 {
  width: 100%;
  height: 100%;
  /* Set height as 100% */
  margin-bottom: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-sm-7 company">
      <h2>this is my title</h2>
      <div class="companyDescription">
        <div class="outer">
          <div class="inner1" id="inner1">
            <article>
              <h5>"The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet
                                        </h5>
              <h5>Some kind of subtitle</h5>
              <h5><a id="readMore" style="cursor: pointer; cursor: hand;">read more...</a></h5>
            </article>
          </div>
          <div class="inner2">
            <article>
              <h5><a id="readLess" style="cursor: pointer; cursor: hand;">...read less</a></h5>
              <h5>As the use of typewriters grew in the late 19th century, the phrase began appearing in typing and stenography lesson books as a practice sentence. Early examples of publications which used the phrase include Illustrative Shorthand by Linda Bronson (1888), How to Become Expert in Typewriting: A Complete Instructor Designed Especially for the Remington Typewriter (1890)
                                        </h5>
              <h5>the last subtitle.</h5>
            </article>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Ответ 7

Вы включили файл jquery-ui-1.10.4.min.js? и является ли порядок всех файлов css js правильным? Потому что один и тот же код с тем же стилем и скриптом работает для меня. Попробуйте этот ниже код.

<!DOCTYPE html>
<html>
<head>
    <title>Scroll</title>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>        
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css">
    <script>
        $(document).ready(function () {
            $('#readMore').click(function () {
                $('.companyDescription').animate({
                    scrollTop: $('#inner1').outerHeight() + 30
                }, 1000);
            });
            $('#readLess').click(function () {
                $('.companyDescription').animate({
                    scrollTop: 0
                }, 1000);
            });
        });
    </script>
    <style>
        .company {
            padding-top: 160px;
            color: #000;
        }

        .companyDescription {
            margin: 20px 0 10px 0;
            overflow:hidden;
        }

        .outer{
            width:100%;
            height:280px;
            top:0;
            position:relative;
        }

        .inner1{
            width:100%;
            height:270px;
            margin-bottom:0px;

        }
        .inner2{
            width:100%;
            height:280px;
            margin-bottom:0px;

        }
    </style>
</head>
<body>
    <div class= "container">
        <div class="row">
            <div class="col-sm-7 company">
                <h2>this is my title</h2>
                <div class="companyDescription" >
                    <div class="outer">
                        <div class="inner1" id="inner1">
                            <h5>"The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet
                            </h5><h5>Some kind of subtitle</h5>
                            <h5><a id="readMore" style="cursor: pointer; cursor: hand;">read more...</a></h5>
                        </div>
                        <div class="inner2">
                            <h5><a id="readLess" style="cursor: pointer; cursor: hand;">...read less</a></h5>
                            <h5>As the use of typewriters grew in the late 19th century, the phrase began appearing in typing and stenography lesson books as a practice sentence. Early examples of publications which used the phrase include Illustrative Shorthand by Linda Bronson (1888), How to Become Expert in Typewriting: A Complete Instructor Designed Especially for the Remington Typewriter (1890)
                            </h5>
                            <h5>the last subtitle.</h5>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

Ответ 8

Вы можете использовать класс clearfix

<div class="clearfix"></div>