我从另一个问题< a href=' https://stackoverflow.com/ questions/4950575/how-to-move-a-div-with-arrow-keys> 上找到这个脚本,这个脚本非常完美。脚本更新了 px 中的元素, 我特别喜欢您通过举起“ 左箭头” 键来移动元素对角的方式 。
现在我的问题是:能否修改脚本, 使脚本设置和更新百分比元素的值?
其原因是我正在开发一个具有响应性设计的网站,我需要将元素留在页面上(并移动)与窗口大小相对。 我试图找出原因,但至今还没有成功。
以下是脚本 :
HTML HTML
<div id="pane">
<div id="box"></div>
</div>
CSS 安保部
#pane {
position:relative;
width:300px; height:300px;
border:2px solid red;
}
#box {
position:absolute; top:140px; left:140px;
width:20px; height:20px;
background-color:black;
}
JavaScript 贾斯克里普特
var pane = $( #pane ),
box = $( #box ),
w = pane.width() - box.width(),
d = {},
x = 3;
function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > w ? w : n;
}
$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });
setInterval(function() {
box.css({
left: function(i,v) { return newv(v, 37, 39); }, //Function should set values in %
top: function(i,v) { return newv(v, 38, 40); } //here for left and top
});
}, 20);
咖啡犯罪
jQuery ->
pane = $( body )
box = $( .myDiv )
w = pane.width() - box.width()
c = [37,38,39,40] # Set key values for arrow keys in an array
d = []
x = 4
newv = (v,a,b) ->
n = parseInt(v, 10) - (if d[a] then x else 0) + (if d[b] then x else 0)
if n < 0 then 0 else if n > w then w else n
$(window).keydown((e) ->
d[e.which] = true
)
$(window).keyup((e) ->
d[e.which] = false
if true not in d and e.which in c #Check that all arrow keys are released
divID = $( .myDiv ).attr( id ) # Grab values from the element
top = $( .myDiv ).css( top )
left = $( .myDiv ).css( left )
setTimeout -> #Set a timeout and then send element values with Ajax to database to preserve state of element for next time window is opened
$.ajax(
type: "PUT"
url: "/url/to/update/database"
data:
positiontop: top
positionleft: left
)
,1000
)
setInterval ->
box.css
left: (i,v) ->
newv(v, 37, 39)
top: (i,v) ->
newv(v, 38, 40)
,40