gpt4 book ai didi

javascript - 我正在尝试使用按钮随意移动 CSS 元素,我尝试使用 offset 并且 onlick 不起作用

转载 作者:行者123 更新时间:2023-11-28 08:25:03 25 4
gpt4 key购买 nike

所以我想根据按钮或功能随意移动 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com