问题
How do I target and item in an iframe thats on my site and change the inline value?
<iframe class="preview_iframe">
<div id="example">
<a id="ex">
<svg fill="#000000"></svg>
</a>
</div>
</iframe>
I need to target an SVG (multiple) in an iframe and change the fill (color) with jquery, how can I do this I tried but it doesn't seem to select it.
Heres the jquery im trying
$("[id^=like_iframe_]").load(function() { var frame = $("[id^=like_iframe_]").contents(); $("svg", frame).css({'fill' : 'red'}); });
And
$("[id^=like_iframe_]").contents().find("svg").css({'fill' : 'red'});
Its selecting the frame, but it's not changing the color of the svg
回答1:
I found that the following (see below) works for me:
<html><head>
<script type="text/javascript" src="Downloads/jquery-1.10.2.min.js"></script>
<script type="text/javascript">function tryit(){
$("iframe[id$=iframe]").contents().find("ellipse").css({fill:"red"});
}</script>
</head><body>
<a href="#" onclick='tryit()'>click here</a><br/>
<iframe id="preview_iframe" src="stackoverflow19846765_iframe.html">
This text won't show if browser supports IFRAMEs(?).</iframe>
</body></html>
File stackoverflow19846765_iframe.html reads:
<html><head></head><body>
<div id="example"> <a id="ex" onclick="alert('clicked svg')">
<svg fill="#000000">
<ellipse cx="110" cy="60" rx="100" ry="50" style="fill:blue" />
</svg>
</a> </div>
</body></html>
I had to use a src attribute for the iframe (and put the source in a separate file). (Otherwise the iframe appeared empty.)
The selector on id does not seem to match(?) the HTML fragment (using class) in your code. I used iframe id= and selected it with id*=iframe.
I had to put something within the svg to see anything happen.
NOTE: When trying the code with local files, only Firefox lets me look into the iframe. Chrome prevents that due to same origin policy on local files.
来源:https://stackoverflow.com/questions/19846765/how-to-target-an-item-in-an-iframe-with-jquery