我想在按下键时提高元素#Object
的速度。
HTML代码:
<path d="M 0,70 A 65,70 0 0,0 65,0 5,5 0 0,1 75,0 75,70 0 0,1 0,70Z" fill="#FF6600">
<animateTransform id="object" attributeName="transform" type="rotate" from="360 0 0" to="0 0 0" dur="3s" repeatCount="indefinite" />
</path>
剧本:
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.keyCode == "38") {
var getTheSpeed = parseInt(document.getElementById("object").dur, 10);
getTheSpeed = isNaN(getTheSpeed) ? 3 : getTheSpeed;
getTheSpeed++;
document.getElementById("object").dur = getTheSpeed;
}
}
我的问题是
dur
不仅采用数字值。必须指定秒“ s”。所以,我实际上不能使用isNaN
属性:(我是JavaScript的初学者^^'
有人有运行此脚本的解决方案吗?
Ty
最佳答案
更改以下几行
var getTheSpeed = parseInt(document.getElementById("object").getAttribute("dur").slice(0,-1), 10);
(这将使用
slice(0,-1)
从“ dur”的当前值中删除s)和
document.getElementById("object").setAttribute("dur",String(getTheSpeed) + "s");
(这将设置新的递增值,并使用字符串连接
+ "s"
在其中添加s)检查一下-希望有帮助^^
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.keyCode == "38") {
var getTheSpeed = parseInt(document.getElementById("object").getAttribute("dur").slice(0, -1), 10);
getTheSpeed = isNaN(getTheSpeed) ? 3 : getTheSpeed;
getTheSpeed++;
document.getElementById("object").setAttribute("dur", String(getTheSpeed) + "s");
alert(document.getElementById("object").getAttribute("dur"));
}
}
<path d="M 0,70 A 65,70 0 0,0 65,0 5,5 0 0,1 75,0 75,70 0 0,1 0,70Z" fill="#FF6600">
<animateTransform id="object" attributeName="transform" type="rotate" from="360 0 0" to="0 0 0" dur="3s" repeatCount="indefinite" />
</path>