【问题标题】:Jquery to show and hide on button click and also move the button on the same clickJquery 在按钮单击时显示和隐藏,并在同一次单击时移动按钮
【发布时间】:2018-04-01 00:29:57
【问题描述】:

我是 Jquery 的初学者,我设法获得了一个显示 div 的按钮和一个在显示 div 时向右移动的按钮。我已经看到了关于切换可见性等的类似问题,但我还需要在点击时移动按钮,但我试图按照他们的逻辑让它工作但没有成功。

但是当我再次点击它时做相反的事情(隐藏 div 并将按钮移回)我无法让它工作。

谁能告诉我哪里出错了?

HTML

<button id="myfilterFunction">Show/Hide</button>

    <div id="filterview">
    <?php echo $column_right; ?></div>
    </div>

Javascript

<script>
        $( "#myfilterFunction" ).click(function() {                                 
            if ($( "#filterview" ).css('display', 'none')) {
            $('#filterview').show();
            $( "#myfilterFunction" ).css('margin-left', '300px');
            }

           if ($( "#filterview" ).css('display', 'block')) {
            $('#filterview').hide();
            $( "#myfilterFunction" ).css('margin-left', '0');
            }
            });
</script>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您没有正确检查元素的可见性。您应该使用.is(":visible") 来检查元素的可见性(使用 jQuery)并相应地处理代码:

    $("#myfilterFunction").click(function () {
        // If the element is visible
        if ($("#filterview").is(":visible")) {
            // Code to process
            $('#filterview').hide();
            $("#myfilterFunction").css('margin-left', '0');
        } else {
            // If the element is not visible
            $('#filterview').show();
            $("#myfilterFunction").css('margin-left', '300px');
        }
    });
    

    $("#filterview").css('display', 'none')用于实际设置元素的css显示属性。

    【讨论】:

    • 非常感谢修复它,并将在未来帮助我!
    • 不错。只是为了进一步参考,这个 SO 问题(和答案)非常适合您正在做的可见性检查here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 2016-10-11
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    相关资源
    最近更新 更多