【问题标题】:Why does this input always remain clickable?为什么这个输入总是保持可点击状态?
【发布时间】:2013-03-05 12:52:24
【问题描述】:

基本上我希望外部 div 接受所有事件,因此 div 中的输入和其他任何内容都不可点击:

<div id="div1">
    <div id="div2">
        <label>Input 1</label>
        <input type="text" id="input1" />
    </div>
</div>

$(document).ready(function() {
    $(document).on('click', '#input1', function(e){
        e.preventDefault();
    };
});

这是无效的示例http://jsfiddle.net/KFWmk/3/

任何帮助表示赞赏:)

【问题讨论】:

    标签: javascript jquery html propagation


    【解决方案1】:

    在较新的 jQuery (1.6+) 中:

    $('div input').prop("readonly", true);
    

    这会将 div 中的所有输入的 HTML readonly 属性设置为 true。

    请注意,使用.attr() 设置属性(布尔值为on 或off 的属性)在jQuery 中已被弃用。

    【讨论】:

    • 实际上似乎更好,但不确定这个来源有多可靠:reference.sitepoint.com/html/input/readonly
    • @qwerty 没错,刚刚在IE6下试过,没问题
    • 谢谢,这似乎适用于输入元素,我认为禁用是选择元素的最佳选择
    【解决方案2】:

    首先,因为您没有包含 jQuery 库。
    第二,因为你有一个 type-o。
    第三,因为焦点是在点击事件之前发出的。 (Prove)

    如果您想让输入字段不可编辑,您可以使用:

    $("input").prop("readonly", true);
    

    或者只是当您在 html 中创建输入字段时:

    <input readonly type="number">
    

    如果您想防止焦点在输入字段上,您可以使用:

    $("input").on("focus", function() {
        $(this).blur();
    }); 
    

    【讨论】:

    • "如果你想阻止焦点" - 使用 readonly 不会阻止焦点,它只会使字段...嗯...只读。也就是说,您仍然可以使用 Tab 键选择字段或使用鼠标选择文本,并且您仍然可以将文本复制到剪贴板 - 您无法更改它。
    【解决方案3】:
    $('div input').attr("readonly", "readonly");
    

    您可以将 div 中的所有输入字段设为只读。

    【讨论】:

    • 使用 .attr() 设置属性在 jQuery 中已被弃用,请查看使用 .prop()
    【解决方案4】:

    你可以这样试试

    $(document).ready(function() {
        $('div input').prop("readonly", true);
    });
    

    【讨论】:

    • 使用 .attr() 设置属性在 jQuery 中已被弃用,请查看使用 .prop()
    • 是的,我使用 .attr 进行了编辑,我们继续设置属性...谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-08-22
    • 2015-10-02
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多