问题
I have the following script that works well in Firefox and Chrome (not sure about other browsers), but it doesn't work at all in IE. It basically opens a popup which appends a div to highlight an item in the window opener. I want it to work across multiple pages on the same site, so I didn't want to add a function to create the div in the main window (window.opener). Sorry I couldn't post a working demo - window.opener doesn't work in a bin.
<button>Open popup</button>
<script type="text/javascript">
$(document).ready(function(){
$(':button').click(function(){
var highlight = "" +
"<button>Click to Add Highlight</button>" +
"<scr"+"ipt type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js'></scr"+"ipt>" +
" <scr"+"ipt type='text/javascript'>" +
" $(':button').click(function(){" +
" $('<div/>', {" +
" 'class': 'highlight'," +
" css: {" +
" position: 'absolute'," +
" height: '50px'," +
" width: '50px'," +
" left: '200px'," +
" top: '200px'," +
" background: '#fff'," +
" opacity: 0.5," +
" zIndex: 99" +
" }" +
" }).appendTo( $(window.opener.document.body) );" +
" })" +
" </scr"+"ipt>";
var w = window.open('','highlighter','toolbar=0,location=0,status=0,width=200,height=100,scrollbars=1,resizable=1');
w.document.write(highlight);
w.document.close();
})
})
</script>
I have also tried to use appendChild without success. I ultimately found this method to work, but it is a horrible solution and causes the page to blink.
if ($.browser.msie){
var d = '<div class="highlight" style="position:absolute;height:50px;' +
'width:50px;left:200px;top:200px;background:#fff;opacity:0.5;' +
'filter:alpha(opacity=50);zIndex:99;"></div>';
window.opener.document.body.innerHTML = window.opener.document.body.innerHTML + d;
}
Anyone know of a better solution?
回答1:
I think I found the problem. It might be a jQuery bug, but I can't tell... I'll post another question to get help.
So I found the solution to this problem by just appending a string. For some reason jQuery in IE won't append an object. So this works:
if ($.browser.msie){
var d = '<div class="highlight" style="position:absolute;height:50px;width:50px;left:200px;' +
'top:200px;background:#fff;opacity:0.5;filter:alpha(opacity=50);zIndex:99;"></div>';
$(window.opener.document.body).append(d);
}
Edit: Pointy solved my problem in another question. It turns out it's not a bug, but IE not allowing you to append an object created outside of the window. His solutions is as follows:
window.opener.$('<div/>', {
'class': 'highlight',
css: {
position: 'absolute',
height: '50px',
width: '50px',
left: '200px',
top: '200px',
background: '#fff',
opacity: 0.5,
zIndex: 99
}
}
But make sure the window.opener is using jQuery v1.4 or greater.
回答2:
You did not open it up
var w = window.open(...);
w.document.open(); //Open the document up
w.document.write(highlight);
w.document.close();
Eric
来源:https://stackoverflow.com/questions/2281784/problems-with-ie-and-appending-to-the-window-opener