我正在构建一个 3x3 益智游戏。最终我想构建它,以便在双击单个片段时可以将其锁定在列表中的位置。不过,现在我专注于构建一个可以改变 class
的函数。当该 block 为 dblclick
时的状态
这是我的代码:
<body>
<div id="puzzleboard">
<ul id="pieces">
<li></li><li ></li><li></li><li ></li><li ></li><li></li><li></li><li></li><li></li>
</ul>
</div>
<script type="text/javascript">
window.onload = populate;
var imgArray = new Array("images/Untitled-0.png","images/Untitled-1.png","images/Untitled-2.png","images/Untitled-3.png","images/Untitled-4.png","images/Untitled-5.png","images/Untitled-6.png","images/Untitled-7.png","images/Untitled-8.png");
var usedImg = new Array()
var itemArray = new Array ("item0", "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8")
var div = document.getElementById("pieces");
var list = document.getElementsByTagName('li')
function populate(){
for (i=0; i<list.length;i++){
var randomNum = Math.floor(Math.random()*imgArray.length);//generates a random #
var img = new Image(); // creates a new image object
img.src = imgArray[randomNum]; //source of the image is based on the random # and correlating item in imgArray
do {
randomNum = Math.floor(Math.random()*imgArray.length);
img.src = imgArray[randomNum]; //generates a new number
} while (usedImg[img.src]); // but only if the source of the image is in used images
usedImg[img.src] = true; //copies img.src to used image
var imgPlace=document.createElement('img'); //instruct it to create an img tag
imgPlace.src=img.src; //defines source
var item = list[i]
list[i].id = itemArray[randomNum];
list[i].appendChild(imgPlace);
};
};
$(list).dblclick(function(){
$(this).toggleClass('ui-state-disabled');
});
$( function() {
$( "#pieces" ).sortable({
items: "li:not(.ui-state-disabled)"
});
});
</script>
这适用于脚本,但我有一个 <img>
在每个 <li>
。页面将加载所有<li>
与 class="ui-sortable-handle"
,当一 block 是 dblclick
时它变成class="ui-sortable-handle ui-state-disabled"
,图像但是当我 dblclick
再次在那一 block 上,它不会变回来。那么我该如何切换<li>
当它是图像时可排序状态?
最佳答案
这对我有用。
$( function() {
$("#pieces").sortable({
items: "li:not(.ui-state-disabled)"
});
$("#pieces li").dblclick(function(){
$(this).toggleClass('ui-state-disabled');
//$(this).children().toggleClass('ui-state-disabled'); //if you want to change property of the image for example opacity
});
});
但是你的代码是一样的,请用浏览器的控制台(通常是F12键)检查一下你的页面的其他脚本中是否有JavaScript错误
关于javascript - 当它是图像时,如何切换 <li> 可排序状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41209017/