我使用SVG矩形来模拟文本输入,另一个用于提交按钮。单击该按钮将警告用户键入的内容。我希望能够在按下退格键时删除内容,并遇到麻烦。
以下是代码:
<svg xmlns="http://www.w3.org/2000/svg" width="100%"
xmlns:xlink="http://www.w3.org/1999/xlink">
<script><![CDATA[
xmlns="http://www.w3.org/2000/svg"
xlink="http://www.w3.org/1999/xlink"
// when a key is pressed call function keypress but first check and see that the
document.documentElement.setAttribute("onkeypress","keypress(evt)")
attention=false; function doit(){attention=true;}
//typing
function keypress(evt){
//declaring variables
newtext=String.fromCharCode(evt.charCode)
text=document.getElementById("inputText")
count=text.textContent.length
if (attention == true){
if (count<13){
text.textContent += newtext
}
}
}
//alert what user typed
function ntext(){
var textValue = document.getElementById('inputText').textContent
alert(textValue + " <-- This is what you typed")
}
//trying to get backspace to delete character
document.onkeydown = backspace;
function backspace()
{
var KeyID = event.keyCode;
switch(KeyID)
{
case 8:
alert("backspace isnt working wahh :/")
text.textContent += newtext.substr(0,newtext.length-1)
break;
case 46:
alert("Delete")
break;
default:
break;
}
}
]]>
</script>
<g>
<rect onclick="doit()" width="115" height="25" x="20" y="20"
style="fill:white;stroke-width:2;stroke:rgb(0,0,0)" />
<text id="inputText" font-size="15" x="22" y="37"></text>
</g>
<g onclick="ntext()">
<rect x="140" y="18" height="30" width="60"
rx="10" ry="10"
style="stroke:#787878; fill: #D0D0D0 "/>
<text font-size="12" x="150" y="37" >Submit</text>
</g>
</svg>
此处位于live webpage。
显然会捕获退格事件,因为按下退格键会触发警报。
我尝试了很多东西,但都无济于事。如何解决这个问题?