首页 > 解决方案 > 为什么我的 ID 容器在 Document.ready 匿名函数中没有从蓝色变为红色

问题描述

我有一个由我们的网站提供商生成的表格。它有一个我访问过的 ID。在 css 中,我的颜色为蓝色,它是隐藏的。我在 document.ready 事件中有代码,单击以使窗体在窗口中居中。. 由于stackoverflow,它完美居中。然后我添加到单击事件以将颜色更改为红色。当我通过单击文档中的标签激活代码时,表单仍然是蓝色的。我并不特别关心颜色,但我正在尝试学习如何操作表单中的其他元素,例如稍后添加关闭按钮。

<script type="text/javascript">
    $(document).ready(function () {
        $("a").click(function () {
            var windowWidth
            var windowHeight
            var formWidth
            var formHeight
            var placementHeight
            var placementWidth
            $("#custom-form-1451559841907633284-p").attr('style', 'display:block;');
            windowWidth = window.innerWidth;
            windowHeight = window.innerHeight;
            formWidth = $('#custom-form-1451559841907633284-p').width();
            formHeight = $('#custom-form-1451559841907633284-p').height();
            placementHeight = (windowHeight - formHeight) / 2;
            placementWidth = (windowWidth - formWidth) / 2;
            $('#custom-form-1451559841907633284-p').css("top", placementHeight);
            $('#custom-form-1451559841907633284-p').css("left", placementWidth);
            $('custom-form-1451559841907633284-p').css('background-color', 'red');
            $('#custom-form-1451559841907633284-p').css('z-Index', '30');
        }); //end of a anchor click
        window.console.log("test of nested anonymous function");
    });
</script>

CSS

#custom-form-1451559841907633284-p
{
    position: fixed; 
    display: none;
    background-color: blue;
}

标签: javascripthtmlcss

解决方案


您在这一行中使用了错误的选择器:

$('custom-form-1451559841907633284-p').css('background-color', 'red');

您忘记了custom-form-1451559841907633284-p前面的哈希,只需将该行替换为以下内容:

$("#custom-form-1451559841907633284-p").css("背景颜色", "红色");

你可以在这里看到一个工作示例: https ://codesandbox.io/s/distracted-lichterman-vus5g


推荐阅读