问题
I am having an issue applying css dynamically to a loaded div using the load()
function. The html being loaded is found, and it is inserted, and I can use a close command. However the css I am trying to apply is not being registered. Everything seems to work fine minus the dynamic css. I think I may have something wrong or an incorrect function here:
Jquery:
$(document).ready(function() {
//Find & Open
$(".projectThumb").click(function(){
htmlName = $(this).find("img").attr("name");
$("#popupContainer").load(htmlName + ".html");
});
//Apply CSS
$(".projectPopup").css({"position": "absolute", "background": "#000", "top": "10%", "left": "10px"});
//Close property
$("a.close").live("click", function(){
$("#popupContainer").empty();
});
});
test.php:
<div id="content">
<div class="projectThumb">
<img src="/img/aeffect_button_static.gif" name="aeffect" />
<p class="title">title</p>
</div>
</div>
<div id="popupContainer"></div>
aeffect.html:
<div class="projectPopup" id="aeffect">
<a class="close">Close ×</a>
<p class="description">Description</p>
</div>
回答1:
You are setting the CSS properties at the wrong time. What you need to do is apply the CSS properties after the load completes using the callback function of the load() method.
$("#popupContainer").load(htmlName + ".html", {}, function(){
$(".projectPopup").css({"position": "absolute", "background": "#000", "top": "10%", "left": "10px"});
});
回答2:
Put the apply CSS in the callback for the .load()
$(document).ready(function() {
//Find & Open
$(".projectThumb").click(function(){
htmlName = $(this).find("img").attr("name");
$("#popupContainer").load(htmlName + ".html", null, function(){
//Apply CSS
$("projectPopup").css({"position": "absolute", "background": "#000", "top": "10%", "left": "10px"});
});
//Close property
$("a.close").live("click", function(){
$("#popupContainer").empty();
});
});
来源:https://stackoverflow.com/questions/1408262/jquery-applying-css-to-load-div