使用JavaScript显示/隐藏'div'

时间:2014-01-12 01:12:05

标签: javascript html onclick

对于我正在做的网站,我想加载一个div,然后隐藏另一个div,然后有两个按钮,可以使用JavaScript在div之间切换视图。

这是我当前的代码

function replaceContentInContainer(target, source) {
  document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}

function replaceContentInOtherContainer(replace_target, source) {
  document.getElementById(replace_target).innerHTML = document.getElementById(source).innerHTML;
}
<html>
<button onClick="replaceContentInContainer('target', 'replace_target')">View Portfolio</button>
<button onClick="replaceContentInOtherContainer('replace_target', 'target')">View Results</button>

<div>
  <span id="target">div1</span>
</div>

<div style="display:none">
  <span id="replace_target">div2</span>
</div>

替换div2的第二个函数不起作用,但第一个函数是。

15 个答案:

答案 0 :(得分:374)

如何显示或隐藏元素:

为了显示或隐藏元素,请操作元素的style property。在大多数情况下,您可能只想更改元素的display property

element.style.display = 'none';           // Hide
element.style.display = 'block';          // Show
element.style.display = 'inline';         // Show
element.style.display = 'inline-block';   // Show

或者,如果你仍然希望元素占用空间(就像你要隐藏表格单元格一样),你可以改为改为元素visibility property

element.style.visibility = 'hidden';      // Hide
element.style.visibility = 'visible';     // Show

隐藏元素集合:

如果要隐藏元素集合,只需遍历每个元素并将元素的display更改为none

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
// Usage:
hide(document.querySelectorAll('.target'));
hide(document.querySelector('.target'));
hide(document.getElementById('target'));

hide(document.querySelectorAll('.target'));

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
<div class="target">This div will be hidden.</div>

<span class="target">This span will be hidden as well.</span>

显示元素集合:

大多数情况下,您可能只是在display: nonedisplay: block之间切换,这意味着在显示元素集合时,以下可能就足够了。< / p>

如果您不希望默认为display,则可以选择将所需的block指定为第二个参数。

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
// Usage:
var elements = document.querySelectorAll('.target');
show(elements);

show(elements, 'inline-block'); // The second param allows you to specify a display value

var elements = document.querySelectorAll('.target');

show(elements, 'inline-block'); // The second param allows you to specify a display value

show(document.getElementById('hidden-input'));

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
<div class="target" style="display: none">This hidden div should have a display of 'inline-block' when it is shown.</div>

<span>Inline span..</span>

<input id="hidden-input" />

或者,显示元素的更好方法是仅删除内联display样式,以便将其恢复到其初始状态。然后检查元素的计算display样式,以确定它是否被级联规则隐藏。如果是,则显示元素。

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}

show(document.querySelectorAll('.target'));

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}
<span class="target" style="display: none">Should revert back to being inline.</span>

<span class="target" style="display: none">Inline as well.</span>

<div class="target" style="display: none">Should revert back to being block level.</div>

<span class="target" style="display: none">Should revert back to being inline.</span>

(如果你想更进一步,你甚至可以模仿jQuery做什么,并通过将元素附加到空白iframe(没有冲突的样式表)来确定元素的默认浏览器样式,然后检索在这样做的过程中,您将知道元素的真正初始display属性值,并且您不必对值进行硬编码以获得所需的结果。)

切换显示:

同样,如果您想切换元素或元素集合的display,您可以简单地迭代每个元素,并通过检查display的计算值来确定它是否可见属性。如果可见,请将display设置为none,否则删除内联display样式,如果仍然隐藏,请将display设置为指定值或硬编码默认值,block

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
// Usage:
document.getElementById('toggle-button').addEventListener('click', function () {
  toggle(document.querySelectorAll('.target'));
});

document.getElementById('toggle-button').addEventListener('click', function () {
    toggle(document.querySelectorAll('.target'));
});

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
.target { display: none; }
<button id="toggle-button">Toggle display</button>

<span class="target">Toggle the span.</span>

<div class="target">Toggle the div.</div>

答案 1 :(得分:80)

您还可以使用jQuery JavaScript框架:

隐藏Div Block

$(".divIDClass").hide();

显示Div Block

$(".divIDClass").show();

答案 2 :(得分:39)

你可以简单地操纵有问题的div的风格......

document.getElementById('target').style.display = 'none';

答案 3 :(得分:18)

您可以使用Js功能隐藏/显示Div。

下面的样本
<script>
    function showDivAttid(){

        if(Your Condition) {

            document.getElementById("attid").style.display = 'inline';
        }
        else
        {
            document.getElementById("attid").style.display = 'none';
        }
    }

</script>

HTML -

<div  id="attid" style="display:none;">Show/Hide this text</div>

答案 4 :(得分:14)

使用样式:

<style type="text/css">
   .hidden {
        display: none;
   {
   .visible {
        display: block;
   }
</style>

在JavaScript中使用事件处理程序优于HTML中的onclick=""属性:

<button id="RenderPortfolio_Btn">View Portfolio</button>
<button id="RenderResults_Btn">View Results</button>

<div class="visible" id="portfolio">
    <span>div1</span>
</div>

<div class"hidden" id="results">
    <span>div2</span>
</div>

JavaScript的:

<script type="text/javascript">

    var portfolioDiv = document.getElementById('portfolio');
    var resultsDiv = document.getElementById('results');

    var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
    var resultsBtn = document.getElementById('RenderResults_Btn');

    portfolioBtn.onclick = function() {
        resultsDiv.setAttribute('class', 'hidden');
        portfolioDiv.setAttribute('class', 'visible');
    };

    resultsBtn.onclick = function() {
        portfolioDiv.setAttribute('class', 'hidden');
        resultsDiv.setAttribute('class', 'visible');
    };

</script>

jQuery可以帮助您轻松操作DOM元素!

答案 5 :(得分:12)

我发现这个简单的JavaScript代码非常方便!

#<script type="text/javascript">
    function toggle_visibility(id) 
    {
        var e = document.getElementById(id);
        if ( e.style.display == 'block' )
            e.style.display = 'none';
        else
            e.style.display = 'block';
    }
</script>

答案 6 :(得分:4)

将您的HTML设置为

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

现在将javascript设置为

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }

答案 7 :(得分:1)

<script type="text/javascript">
    function hide(){
        document.getElementById('id').hidden = true;
    }
    function show(){
        document.getElementById('id').hidden = false;
    }
</script>

答案 8 :(得分:1)

简单设置ID的样式属性:

显示隐藏的div

<div id="xyz" style="display:none">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='block';  // to hide

隐藏显示的div

<div id="xyz">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='none';  // to display

答案 9 :(得分:1)

使用 Button 向上滚动的简单示例。仅当 javascript 处于活动状态时才会滚动,即 event 监听 scroll type

document.getElementById('btn').style.display='none'

window.addEventListener('scroll', (event) => {
    console.log(scrollY)
    document.getElementById('btn').style.display='inline'
})
a
long<br>
text<br>
comes<br>
long<br>
text<br>
again

<button id=btn class = 'btn btn-primary' onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>

Live in action here

答案 10 :(得分:0)

对于使用卤素灯的人来说,Purescript回答:

import CSS (display, displayNone)
import Halogen.HTML as HH
import Halogen.HTML.CSS as CSS

render state = 
  HH.div [ CSS.style $ display displayNone ] [ HH.text "Hi there!" ]

如果你&#34;检查元素&#34;,你会看到如下内容:

<div style="display: none">Hi there!</div>

但没有像预期的那样在屏幕上显示任何内容。

答案 11 :(得分:0)

简单功能需要使用JavaScript实现显示/隐藏'div'

<a id="morelink" class="link-more" style="font-weight: bold; display: block;" onclick="this.style.display='none'; document.getElementById('states').style.display='block'; return false;">READ MORE</a>


<div id="states" style="display: block; line-height: 1.6em;">
 text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here  
    <a class="link-less" style="font-weight: bold;" onclick="document.getElementById('morelink').style.display='inline-block'; document.getElementById('states').style.display='none'; return false;">LESS INFORMATION</a>
    </div>

答案 12 :(得分:0)

我发现了这个问题,最近我正在使用Vue.js实现一些UI,因此这是一个很好的选择。

首先,当您单击“查看配置文件”时,您的代码未隐藏am4core.useTheme(am4themes_animated); am4core.useTheme(function customTheme (object) { // Identify the instances if (object instanceof am4core.Tooltip && object.label) { object.autoTextColor = false; object.label.fill = am4core.color("#FFFFFF"); } }); 。您正在用target覆盖内容target

div2
let multiple = new Vue({
  el: "#multiple",
  data: {
    items: [{
        id: 0,
        name: 'View Profile',
        desc: 'Show profile',
        show: false,
      },
      {
        id: 1,
        name: 'View Results',
        desc: 'Show results',
        show: false,
      },
    ],
    selected: '',
    shown: false,
  },
  methods: {
    showItem: function(item) {
      if (this.selected && this.selected.id === item.id) {
        item.show = item.show && this.shown ? false : !item.show;
      } else {
        item.show = (this.selected.show || !item.show) && this.shown ? true : !this.shown;
      }
      this.shown = item.show;
      this.selected = item;
    },
  },
});

答案 13 :(得分:0)

您可以使用jQuery .toggle()轻松实现这一目标。

Event(() => SomeSagaEvent, x => x.CorrelatedById(m => m.Message.Id))
$("#btnDisplay").click(function() {
  $("#div1").toggle();
  $("#div2").toggle();
});

答案 14 :(得分:0)

相反,您的两个函数都将toggle函数与后面的正文一起使用

this[target].parentNode.style.display = 'none'
this[source].parentNode.style.display = 'block'

function toggle(target, source) {
  this[target].parentNode.style.display = 'none'
  this[source].parentNode.style.display = 'block'
}
<button onClick="toggle('target', 'replace_target')">View Portfolio</button>
<button onClick="toggle('replace_target', 'target')">View Results</button>

<div>
  <span id="target">div1</span>
</div>

<div style="display:none">
  <span id="replace_target">div2</span>
</div>