我从stackoverflow 上的另一个问题中得到了这个脚本,它运行良好。该脚本以 px 为单位更新元素,我特别喜欢通过按住向上+向左箭头键对角移动元素的方式。
我现在的问题是:是否可以更改脚本,以便以百分比设置和更新元素的值?
这样做的原因是我正在开发一个具有响应式设计的网站,并且我需要元素相对于窗口大小保持(和移动)在页面上。我试图弄清楚,但到目前为止还没有成功。
这是脚本:
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