3

我想在我的页面中实现一个框,按需显示:用户按下按钮,显示 div。

作为我想要实现的视觉示例,请查看 jsfiddle 上的键盘快捷键框(左下角):http: //jsfiddle.net/

现在我不确定我应该以哪种方式做到这一点:

  • 立即创建 div 并将其设置为 display: none 而不需要
  • 编写一个脚本,通过 JS 添加 div
  • 编写一个从外部 .html 文件加载它的脚本

你会推荐什么方法?

更新

如果我有 15 个在页面加载时未显示但应按需添加的不同框怎么办?当然,它会起作用,但我们可以称它为“良好做法”来简单地隐藏我们不想看到的每个元素吗?

4

3 回答 3

3

只需将 div 添加到HTML并将 css 属性默认设置displaynone,然后使用 jquery 在单击时将其淡入,如下所示:

 $('#some_button').click(function(){
     $('.hidden_box').fadeIn();
 });

工作示例

试试这个工作jsfiddle

于 2012-12-21T13:37:19.980 回答
2

Update: You recently modified the question to ask about 15 or so elements that aren't immediately needed. In this case, with so many non-immediate elements, I would probably consider creating them on the fly when you need them, but always checking for their existence prior so you don't end up re-creating them over and over.


I would just load the element in when the page loads:

<div id="box"></div>

Style it, having it be non-visible by default:

​#box {
    position: fixed;
    top: 10%; left: 10%;
    width: 80%; height: 80%;
    background: red;
    display: none;
}​

And then wire-up the logic to show it on some event, perhaps pressing of the spacebar:

var $box = $("#box");

$(document).on({
    keydown: function (event) {
        if (event.which === 32 && $box.is(":not(:visible)"))
            $box.stop().fadeIn();
    },
    keyup: function (event) {
        if (event.which === 32) 
            $box.stop().fadeOut();
    }
});

And voila: http://jsfiddle.net/GfMsd/

Or you could base it off of the clicking of another element, like jsFiddle has done:

$(".toggle").on("click", function (event) {
    $("#box").stop().fadeToggle();
});​

Demo: http://jsfiddle.net/GfMsd/1/

于 2012-12-21T13:39:09.483 回答
1

一个没有 jQuery 的答案,只是为了确保原生 JS 没有被低估;-)

创建一个div包含您想要的任何内容,并将其放置在您最终想要的任何位置,然后将其隐藏:

<div id="hiddenDiv" style="display:none">Some content here</div>

然后,在按钮上添加一个事件监听器来切换它的可见性。

document.getElementById('showDivButton').addEventListener('click', toggleDiv);
var div = document.getElementById('hiddenDiv');

function toggleDiv(){
    if(div.style.display == 'block') {
        div.style.display = 'none';
    }else{
        div.style.display = 'block';
    }
}
于 2012-12-21T13:38:18.257 回答