在OSX 10.12.6下测试和使用Safari 11.0.1;
我想在oninput="function()"
设置<div>
时使用contenteditable="true"
。 Bare-bones测试页面案例适用于<textarea>
,但不适用于<div>
。这是测试代码;从 tpagecontentx 更改脚本第一个var load getElementById
参数到 dpagecontentx ,看它是否适用于textarea而不能使用div。
<HTML>
<HEAD>
<SCRIPT>
function onCharInput()
{
var conpagechars = document.getElementById("tpagecontentx").value;
var conpagecharcount = conpagechars.length.toString();
document.getElementById("pccount").innerHTML = conpagecharcount;
}
</SCRIPT>
<title>Editor</title>
</HEAD>
<BODY>
<center>
<div id="dpagecontentx" oninput="onCharInput()" name="dpagecontent" contenteditable="true" style="font-family: Courier; padding: .5em; text-align: left; border-color: #000000; border-width: 1px; border-style: solid; width: 60em; height: 24em;"></div>
<TEXTAREA id="tpagecontentx" oninput="onCharInput()" NAME="tpagecontent" ROWS=10 COLS=80>foo</TEXTAREA>
</center>
<p>
Content Size: <span id="pccount"></span>
</p>
</BODY>
</HTML>
答案 0 :(得分:1)
oninput
事件仅在<input>
,<select>
或<textarea>
元素的值发生更改时触发,对于<div>
标记您可以使用keyup
事件来检测更改,以下是工作示例:
function onCharInput(e)
{
// here I use tagName property to get the element content
// according to its type
if (e.target.tagName === 'DIV') {
var conpagechars = document.getElementById("dpagecontentx").innerText;
} else {
var conpagechars = document.getElementById("tpagecontentx").value;
}
var conpagecharcount = conpagechars.length.toString();
document.getElementById("pccount").innerHTML = conpagecharcount;
}
&#13;
<center>
<div id="dpagecontentx" onkeyup="onCharInput(event)" name="dpagecontent" contenteditable="true" style="font-family: Courier; padding: .5em; text-align: left; border-color: #000000; border-width: 1px; border-style: solid; width: 60em; height: 24em;"></div>
<TEXTAREA id="tpagecontentx" oninput="onCharInput(event)" NAME="tpagecontent" ROWS=10 COLS=80>foo</TEXTAREA>
</center>
<p>
Content Size: <span id="pccount"></span>
</p>
&#13;