当使用CSS display:none时,如何保持在DOM中分配的空间 [英] how can I keep the space allocated in DOM when using CSS display:none

查看:193
本文介绍了当使用CSS display:none时,如何保持在DOM中分配的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道display:none和visibility:隐藏的功能。由于某些原因,我必须使用display:none,并且仍然要保留为DOM中的元素分配的空间,以便它不会影响其旁边的其他元素。可能吗?

I am aware of display:none and visibility:hidden functionality. Due to some reason I have to use display:none and still want to keep the space allocated for the element in DOM so that it doesn't affect other elements next to it. Is it possible?

这是一个后续问题,因为我已经指出,问题是因为display:none属性。链接到原始问题的是此处

This is a follow up question as I have pointed out the issue is because of display:none property. Link to the original question is HERE

更新:根据TJ的要求Crowder,我在这里包含了我原来问题的所有相关细节。

UPDATE: As requested by T.J. Crowder, I am including all the relevant details from my original question over here.

你能告诉我如何为我的功能添加一个漂亮的褪色效果,

Can you tell me how can I add a nice fade effect for smoother animation to my function instead of setting visibility hidden / visible at an regular interval.

我不是在寻找一个插件或添加jQuery UI库。

I am not looking for a plugin or add jQuery UI library.

我的JS

setBlinkingInterval: function(elem, event) {
    if (intervalIdForBlinking != 0) 
        window.clearInterval(intervalIdForBlinking);

    $(elem).show();
    intervalIdForBlinking = setInterval(function() {
       if (eventsObj.eventIsFinished(event)) {
          timer.setClosedStatus(elem, event);
       }
       else {
          if (elem.css('visibility') == 'hidden') 
             elem.css('visibility', 'visible');
         else 
             elem.css('visibility', 'hidden');
       }
   }, 500);
} 

更新1:HTML标记以澄清一个答案

Update 1: HTML markup in order to clarify one answer

$('<span/>')
            .append('<div id="closing_blink" class="yellowText" style="display:none;">' + closing + '&nbsp;</div>')
            .append(date.formatFullDate(new Date(event.timeUtc)) + timezone)
            .append('<br/>')
            .append((weatherInfo != '' && trackInfo != '') ? '<div class="whiteText">' + weather + '</div>' + '<div class="orangeText">' + weatherInfo + '</div>' + '&nbsp;' + '<div class="whiteText">' + track + '</div>' + '<div class="orangeText">' + trackInfo + '</div>' : '')
            .appendTo(rightTd);

所以在根据提供的答案实施解决方案后,

案例1:使用我的原始解决方案时(效果很好)

Case 1: When using my original solution (It works fine)

屏幕记录器链接这里

案例2:当使用淡入/淡出方法(显示问题)

Case 2: When using fade in/out method (Display issue)

屏幕录制器链接这里

情况3:使用切换方法(显示问题)

Case 3: When using toggle method (Display issue)

屏幕录制器链接此处

有任何快速解决方法可解决显示问题吗?

Is there any quick fix to solve the display issue?

下面是一个JS函数生成的完整的HTML:
drawRaceHead:function(event){

Here is the complete HTML up generated by a JS function drawRaceHead: function(event) {

// Returning all race numbers to default values
styling.makeAllRaceNumbersUnselected();

// Make the race number active (including Racing Specials)
styling.makeCurrentEventNumberSelected(event)

// Race info
$("#raceInfo").html('');
$("#raceInfo").append($('<table/>').append($('<tr/>')))
var leftTd = $('<td style="width: 295px"/>')
        .appendTo($('#raceInfo')),
    rightTd = $('<td/>')
        .appendTo($('#raceInfo'));
// If not Racing Specials category
if (event.parentCategoryId != 2863) leftTd.html(raceFullName + '&nbsp;' + event.name)
else leftTd.html(event.name);

$('<div id="closing_time" style="display:none"/>')
    .appendTo(leftTd)

// Date, time, weather, track
var weatherInfo = '', trackInfo = '';
if (event.markets.length > 0) {
    weatherInfo = (event.markets[0].weather == null) ? '-' : event.markets[0].weather;
    trackInfo = (event.markets[0].track == null) ? '-' : event.markets[0].track;
}

var isMSIE = /*@cc_on!@*/false;
var ieVersion = (function(reg) { return isMSIE && navigator.userAgent.match(reg) ? RegExp.$1 * 1 : null; })(/MSIE\s([0-9]+[\.0-9]*)/);

if (isMSIE && ieVersion < 11) {
    timezone = '';
}
else {
    var regExp = /\(([^)]+)\)/, timezone = (regExp.exec(new Date)[1]).split(' ')[0];
    timezone = ' (' + timezone + ')';
}

$('<span/>')
    .append('<div id="closing_blink" class="yellowText" style="display:none;">' + closing + '&nbsp;</div>')
    .append(date.formatFullDate(new Date(event.timeUtc)) + timezone)
    .append('<br/>')
    .append((weatherInfo != '' && trackInfo != '') ? '<div class="whiteText">' + weather + '</div>' + '<div class="orangeText">' + weatherInfo + '</div>' + '&nbsp;' + '<div class="whiteText">' + track + '</div>' + '<div class="orangeText">' + trackInfo + '</div>' : '')
    .appendTo(rightTd);

},

推荐答案

注意:此答案有根据OP的更新部分。

Note: This answer has sections, based on updates from the OP.

而不是 display:none ,请使用 visibility:hidden 。隐藏元素,但元素仍占用布局中的空间。

Instead of display: none, use visibility: hidden. That hides the element, but the element still takes up space in the layout.

您可以通过比较 this jsbin using display:none with 这一个使用 visibility:hidden

You can see the difference by comparing this jsbin using display: none with this one using visibility: hidden.

使用此HTML:

<div>This is above</div>
<div id="toggleme">This is the one that toggles</div>
<div>This is below</div>

第一种用途:

(function() {
  "use strict";
  var toggleme = document.getElementById("toggleme");
  setInterval(function() {
    if (toggleme.style.visibility === "hidden") {
      toggleme.style.visibility = "";
    }
    else {
      toggleme.style.visibility = "hidden";
    }
  }, 400);
});

而第二个用途:

(function() {
  "use strict";
  var toggleme = document.getElementById("toggleme");
  setInterval(function() {
    if (toggleme.style.display === "none") {
      toggleme.style.display = "block";
    }
    else {
      toggleme.style.display = "none";
    }
  }, 400);
});






使用 fadeOut 隐藏元素。当然,这将完成后设置 display:none 。 As Arun指出,你可以使用 fadeTo 来动画 opacity ,直到 0 ,这与设置 visibility:hidden 的效果相似: Live Copy


You've said in a comment below you're using fadeOut to hide the element. That will, of course, set display: none when done. As Arun points out, you can use fadeTo instead, which animates opacity down to 0, which has a similar effect to setting visibility: hidden: Live Copy

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>fadeTo</title>
</head>
<body>
<div>This is above</div>
<div id="hideme">This is the one that toggles</div>
<div>This is below</div>
  <script>
    $("#hideme").fadeTo("slow", 0);
  </script>
</body>
</html>

另一个选择是在 fadeOut 更改显示可见性 Live Copy

Another option is to use the "complete" callback on fadeOut to change display and visibility: Live Copy

$("#hideme").fadeOut(function() {
  $(this).css({
    display: "",
    visibility: "hidden"
  });
});






您已询问如何应用上述到你的代码。代码对我来说看起来过于复杂(不确定整个 eventObj 是什么),但这里有一些我认为你可以随时适应: Live Copy


You've asked how you can apply the above to your code. The code looks overly-complex to me (not sure what the whole eventObj thing is about), but here's something I think you can readily adapt: Live Copy

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>faded blinking</title>
</head>
<body>
<div>This is above</div>
<div id="toggleme">This is the one that toggles</div>
<div>This is below</div>
<input type="button" id="btnStartStop" value="Start">
  <script>
    (function() {
      var obj = {
        startBlinking: function($elem) {
          if ($elem.data("blinking")) {
            return;
          }
          $elem.data("blinking", true);
          fadeToZero();

          function fadeToZero() {
            if ($elem.data("blinking")) {
              $elem.fadeTo("slow", 0, fadeToFull);
            }
          }
          function fadeToFull() {
            if ($elem.data("blinking")) {
              $elem.fadeTo("slow", 1, fadeToZero);
            }
          }
        },
        stopBlinking: function($elem) {
          $elem.data("blinking", false);
        }
      };

      $("#btnStartStop").click(function() {
        if (this.value === "Start") {
          obj.startBlinking($("#toggleme"));
          this.value = "Stop";
        }
        else {
          obj.stopBlinking($("#toggleme"));
          this.value = "Start";
        }
      })
    })();
  </script>
</body>
</html>

这篇关于当使用CSS display:none时,如何保持在DOM中分配的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆