![](/img/trans.png)
[英]How to drag and drop a div changing the css left and top attributes in HTML 5?
[英]Is there a way I can find a div element by both its css 'left' and 'top' attributes?
我有一個div列表,如下所示:
<div class="blockattribute" id="1" style="background-color: rgb(217, 217, 217); left: 0px; top: 0px;"></div>
我在網格上有一堆這些,作為我的填充算法的一部分,我想選擇left
和top
相鄰網格作為我的x和y坐標。 到目前為止,我似乎無法弄清楚如何讓這個工作。 有沒有人建議如何做到這一點?
從stackoverflow問題我嘗試了以下選擇器:
$("div['style=left: 0px; top:0px;']");
我認為這很接近,但我收到此錯誤:
jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: div['style=left: 0px; top:0px;']
怎么樣的東西:
$(".blockattribute").filter(function(ind,el){return $(el).offset().left == your_value && $(el).offset().top == your_value})
或者如果您打算使用css值,您可以執行以下操作:
$(".blockattribute").filter(function(ind,el){return $(el).css("left") == your_value+"px" && $(el).css("top") == your_value2+"px"})
你選錯了。 實現此目的的一種方法是迭代divs
並檢查其left
和top
值。
$(function() { var selectDiv = function(left, top) { var $arrDiv = []; $('div.blockattribute').each(function(i, v) { var $div = $(v); $arrDiv.push($div); }); for (var i = 0; i < $arrDiv.length; i++) { var $div = $arrDiv[i]; var offset = $div.offset(); if (offset.left === left && offset.top === top) { return $div; } } return null; } var $selectedDiv = selectDiv(20, 20); console.log($selectedDiv.attr('id')); });
.blockattribute { width: 20px; height: 20px; display: block; position: absolute; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="blockattribute" id="1" style="background-color: rgb(217, 217, 217); left: 0px; top: 0px;"></div> <div class="blockattribute" id="2" style="background-color: rgb(17, 17, 17); left: 20px; top: 20px;"></div> <div class="blockattribute" id="3" style="background-color: rgb(121, 121, 121); left: 40px; top: 40px;"></div>
注意:檢查Evan的答案,該答案比此更清晰。
首先,你的代碼$("div['style=left: 0px; top:0px;']");
在語法上是無效的。 它需要圍繞屬性值引用,如下所示:
$('div[style="left: 0px; top:0px;"]');
話雖如此,它仍然不會得到你想要的結果,因為你的內聯風格必須完全匹配 。
為了更接近你可以使用通配符屬性選擇器來獲得這樣的內聯樣式的一部分,雖然它真的非常挑剔,因為單個空格會導致失敗。
$('div[style*="left: 0px; top: 0px"]').html('test345');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="blockattribute" id="1" style="background-color: rgb(217, 217, 217); left: 0px; top: 0px;">test 123</div>
這里有更多內容: https : //css-tricks.com/attribute-selectors/#rel-anywhere 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.