作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我想根据按钮或功能随意移动 css 元素,实际上我打算按像素或根据比例增加它们,像素的百分比。
无论如何,我知道元素的起始位置,例如。顶部和左侧,我指定它们,我想要的是能够随意为顶部/左侧提供一个新坐标,例如单击按钮。 “移动一个像素”
我不确定我是否遗漏了一些重要的东西;我想我必须将 AJAX 用于实时/动态
这是我假设具有 id #object 的 div 元素存在并且当前位于顶部:300px,左侧:300px;
我想把它移到顶部:301px; 301像素;单击一次,然后单击第二次 top: 302px;左:302px;等等……
这段代码的一部分不是必需的,我在偏移量上使用了 JQuery 教程的代码
<script>
$( "*", document.body ).click(function( event ) {
var offset = $( this ).offset();
event.stopPropagation();
$( "#result" ).text( this.tagName +
" coords ( " + offset.left + ", " + offset.top + " )" );
});
function moveByOnePixel(){
var offset = $( #object ).offset();
var x = offset.left;
var y = offset.top;
$( "#object" ).offset({ top: y+1, left: x+1 });
}
</script>
<button onclick="moveByOnePixel">move up</button>
最佳答案
您的示例接近解决方案,因此我在下面提供了一个解决方案。我注意到的一件大事是您没有将 #object
括在引号中(在您的 moveByOnePixel()
函数的第一行)。
首先,这是我对 #object
元素的一般假设(显然只是一个例子——重要的部分是它的 top
和 left
属性为 300px):
<div id="object" style="position: absolute; width: 100px; top: 300px; left: 300px;">hello</div>
<!-- added 'thebutton' as an ID to make the control easy to reference in JS -->
<button id="thebutton">move up</button>
这是 JavaScript:
$('#thebutton').click(function( event ) {
moveByOnePixel();
});
function moveByOnePixel(){
var offset = $('#object').offset(); // #object needs to be enclosed in quotes
// adding values to the top property does NOT move an element up, it moves it DOWN. Hence, I am *subtracting* in this example
$('#object').offset({ top: offset.top - 1, left: offset.left - 1 });
}
关于javascript - 我正在尝试使用按钮随意移动 CSS 元素,我尝试使用 offset 并且 onlick 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28554248/
我是一名优秀的程序员,十分优秀!