![](/img/trans.png)
[英]How to swap CSS - Cannot get element stylesheet [object HTMLLinkElement]
[英]How to move an element styled by CSS stylesheet?
我有要移動的圖像。 如果我具有以下HTML,則可以使用javascript移動元素:
<html>
<head>
<title>Snake</title>
<script type="text/javascript" src="snake.js"></script>
<!-- <link type="text/css" href="snake.css"> -->
</head>
<body onKeyPress="ProcessKeypress(event);">
<p><img id="snake" style="z-index: 0; left: 300px; position: absolute; top: 250px"
float=top border=0 hspace=0 src="snake.gif"></p>
</body>
但是我想使用CSS監視image元素。 當我這樣做時,我的代碼無法移動圖像。 下面是我想使用的HTML和CSS。
<html>
<head>
<title>Snake</title>
<script type="text/javascript" src="snake.js"></script>
<link type="text/css" href="snake.css">
</head>
<body onKeyPress="ProcessKeypress(event);">
<p><img id="snake" src="snake.gif"></p>
</body>
@CHARSET "UTF-8";
img {
z-index: 0;
left: 300px;
position: absolute;
top: 250px;
float: top;
border: 0;
hspace: 0;
}
下面的JavaScript是我用來移動圖像的東西。 任何和所有幫助表示贊賞。
function moveObj(name, Xpix, Ypix)
{
obj = document.getElementById(name);
px = parseInt(obj.style.left) + Xpix;
py = parseInt(obj.style.top) + Ypix;
obj.style.left = px;
obj.style.top = py;
}
function ProcessKeypress(e)
{
var myObj = 'snake';
var moveBy = 10;
if(e.keyCode === 97) {
moveObj(myObj, -moveBy, 0);
}
else if(e.keyCode === 100) {
moveObj(myObj, moveBy, 0);
}
else if(e.keyCode === 115) {
moveObj(myObj, 0, moveBy);
}
else if(e.keyCode === 119) {
moveObj(myObj, 0, -moveBy);
}
}
我不確定您的代碼是否為復制粘貼,但是您需要關閉鏈接標記才能鏈接到CSS。
<link rel="stylesheet" type="text/css" href="location" />
但這是沒有意義的。 這是轉貼,因此我將其標記為。 請參閱為什么element.style.left返回NaN?
那應該回答你的問題。 當我處理您的代碼時,它回答了我的問題,這很有意義。 祝好運。
obj.style.left
訪問內聯定義的樣式屬性。
這是您的純JavaScript解決方案
function getStyleProp(elem, prop){
if(window.getComputedStyle)
return window.getComputedStyle(elem, null).getPropertyValue(prop);
else if(elem.currentStyle) return elem.currentStyle[prop]; //IE
}
function moveObj(obj, Xpix, Ypix) {
obj.style.left = parseInt(getStyleProp(obj,'left')) + Xpix+"px";
obj.style.top= parseInt(getStyleProp(obj,'top')) + Ypix + "px";
}
function ProcessKeypress(e) {
var myObj = document.getElementById("snake");
var moveBy = 10;
switch(e.charCode) {
case 97: moveObj(myObj, -moveBy, 0); break;
case 100: moveObj(myObj, moveBy, 0); break;
case 115: moveObj(myObj, 0, moveBy); break;
case 119: moveObj(myObj, 0, -moveBy); break;
}
}
我還使用jQuery解決了您的案例: 演示
function moveObj(obj, Xpix, Ypix) {
obj.css('left', parseInt(obj.css('left')) + Xpix);
obj.css('top', parseInt(obj.css('top')) + Ypix);
}
function ProcessKeypress(e) {
var myObj = $("#snake"); //It will be better if it is cached
var moveBy = 10;
switch(e.charCode) { //used Switch for better manageability
case 97: moveObj(myObj, -moveBy, 0); break;
case 100: moveObj(myObj, moveBy, 0); break;
case 115: moveObj(myObj, 0, moveBy); break;
case 119: moveObj(myObj, 0, -moveBy); break;
}
}
$(document).on('keypress', ProcessKeypress);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.