我試圖在ajax成功響應(yīng)之后應(yīng)用jquery.css效果。我想這不起作用,因?yàn)槲覐淖罱傻脑刂蝎@取高度,然后將其應(yīng)用到另一個(gè)最近生成的元素。我嘗試將.opts div移到底部,基于.col-4div的高度,這是動(dòng)態(tài)的。
這是鋼筆:https://codepen.io/Pancuatico/pen/abpOeZy
當(dāng)您打開(kāi)pen時(shí),您可以在控制臺(tái)中應(yīng)用以下代碼:$(".opts").css("margin-top",$(".col-4").height());
,您將看到它工作得非常完美,但是,在ajax成功響應(yīng)之后,如何正確地使它工作呢?
Edit
我將把我的js代碼放在這里,這樣你就可以看到我的錯(cuò)誤在哪里了。
$(document).ready(function(){
loadImgs();
});
function loadImgs(){
$.post("anurl.php",function(data){
//Some process with the data here
//...
var out = "<div class='col-4'><img src='imgpathalt' alt='imgpath'></div>";
out += "<div class='col-2'>";
out += "<img src='imgpath2' alt='imgpath2alt'>";
out += "<div class='opts'>";
out += "<button>add</button>";
out += "<button>rm</button>";
out += "</div>";
out += "</div>";
$(".row").html(out);
var col4Height = $(".col-4").height();
$(".opts").css("margin-top",col4Height); //this does not work
});
}
原因是,當(dāng)您添加該元素的
margin-top
時(shí),圖像仍在加載。所以.col-4
的高度只是當(dāng)時(shí)按鈕的大小。您必須等待圖像加載完畢,然后將邊距更新為.col-4
的高度。一個(gè)更好的方法是動(dòng)態(tài)地創(chuàng)建元素,而不是將其作為html放入字符串中。這樣就可以用-
更新圖像后的邊距是loaded-
但是,您可以在具有html
onload
屬性的代碼中獲得結(jié)果。