简体   繁体   English

在按钮内输入; 防止输入点击触发按钮点击但仍然能够输入值

[英]Input inside a button; prevent input click to fire button click but still be able to enter value

I have an input inside a button.我在按钮内有一个输入。 I want the uset to be able to click in the input, enter some value, and then click the outside button.我希望用户能够单击输入,输入一些值,然后单击外部按钮。

<button onclick="button()">button
    <input onclick="input()"></input>
</button>

The problem however is that the default behavior is that clicking input will fire the button input as well because of obvious reason (input being inside the button).然而,问题是默认行为是,由于显而易见的原因(输入在按钮内),单击输入也会触发按钮输入。

So I tried to suppress the input's event from firing up and propagating所以我试图抑制输入的事件触发和传播

button.onclick = function () {
    alert('button was pressed');
}
input.onclick = function (e) {
    e.preventDefault();
    e.stopPropagation();
    return false;
    alert('input was pressed');
}

but it also prevents anything from being entered into the input!但它也可以防止任何东西被输入到输入中! or atleast it's not visible.或者至少它不可见。 Probably because I fiddled with the input's default event handling.可能是因为我摆弄了输入的默认事件处理。

Is there a way to click into the input, not have the button fire its own click event (ie button stays independent (even though I've placed input inside of it)), and have the input work like it would've normally?有没有办法点击输入,而不是让按钮触发它自己的点击事件(即按钮保持独立(即使我已经将输入放入其中)),并且让输入像往常一样工作?

http://jsfiddle.net/laggingreflex/wmcrhLoz/ http://jsfiddle.net/laggingreflex/wmcrhLoz/

Here you go: http://jsfiddle.net/wmcrhLoz/2/给你: http : //jsfiddle.net/wmcrhLoz/2/

You just need e.stopPropagation();你只需要e.stopPropagation(); in the input to stop the click event from bubbling to parent elements.在输入中阻止单击事件冒泡到父元素。

Your text is not visible because it is white.您的文本不可见,因为它是白色的。 Change the color of the text in the input to black and it's fine.将输入中文本的颜色更改为黑色就可以了。

#input {
    color: #000;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM