使div的宽度因jQuery而异

时间:2017-03-30 00:53:22

标签: jquery html css width

我有一个div,我通过以下函数每隔半秒生成一次内容:

function ClockAndCalendar() {
  var da = new Date();
  var hours = da.getHours();
  var minutes = da.getMinutes();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var actualTime = hours + ':' + minutes + ampm;
  var wd = weekday[da.getDay()];
  var month = mon[da.getMonth()];
  var curDate = da.getDate();
  var suffix = ending[da.getDate() - 1];
  var timeAndDate = (actualTime + " " + wd + ", " + month + " " + curDate + suffix + ", " + y);
  var newDiv = $('#date-and-time').text(timeAndDate);

  return newDiv;
}
var getTimeDateCalendar = setInterval(ClockAndCalendar, 500);

div #date-and-time嵌套在以下div中,如下所示:

 <div id="calDateTimeBox">
      <i id="clock-link" class="fa fa-calendar" aria-hidden="true" data-title="Click to show calendar."></i>
      <div id="date-and-time">10:06PM Wednesday, March 29th, 2017</div>
    </div>

#calDateTimeBox#clock-link有CSS:

#calDateTimeBox {
  position: absolute;
  top: 40px;
  margin-left: -357px; 
  width: 340px;
  height: auto;
  font-family: 'Many Secrets';
  font-size: 20px;
  letter-spacing: 1px;
  line-height: 1.2;
  color: #FFF;
  background: rgba(0, 0, 0, 0.75);
  text-shadow: 4px 4px 1px #000;
  border-radius: 5px;
  text-align: center;
  padding: 10px 20px;
  pointer-events: none;
  opacity: 0;
}

#clock-link {
  font-family:'FontAwesome';
  float: left;
  margin-right: 10px;
  margin-left: 5px;
}

当时间和日期在较长的一侧时,div看起来像这样:

enter image description here

但我希望它看起来像这样:

enter image description here

使用jQuery是否有可能在内容溢出到第二行时调整div?如果是这样,我将如何实现这种效果?

1 个答案:

答案 0 :(得分:0)

更改

#calDateTimeBox {
   width: 340px;
}

为:

#calDateTimeBox {
   min-width: 340px;
}

问题似乎已经解决了。如果父容器的宽度不足以容纳它,这仍然会使日期转到另一行。

您还可以添加:

#date-and-time {
   white-space: nowrap;
}

但我不建议这样做,因为你的文本将被截断/显示在div容器之外。