Alternate text for iframes

被刻印的时光 ゝ 提交于 2019-12-18 08:09:12

问题


We have alternate text, alt attribute, for an img tag in HTML, which will show up when the image doesn't come up. I tried using the tag with iframe too.

<iframe src="www.abc.com" alt="Web site is not avaialable">

But the alternate text doesn't come up when src="" is given. Just wanted to know if I can achieve alternate text in any other way, if the src is not given ?


回答1:


Since my first attempt misunderstood your question, let's try this instead:

<script>
$(function () {

    $("iframe").not(":has([src])").each(function () {

    var ifrm = this;

    ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;

    ifrm.document.open();
    ifrm.document.write($(this).attr("alt"));
    ifrm.document.close();

    });

});
</script>

This will read the "alt" tag value for any iframe with either no src attribute or a src attribute with a blank value, and write the alt text into the body of that iframe.

Assist from Write elements into a child iframe using Javascript or jQuery




回答2:


The <iframe> element doesn't support an alt attribute, but it does support longdesc. Still, the HTML specification does not dictate how browsers handle long description (or alternate) text. The only way to guarantee any specific behavior is to use JavaScript. Here is an untested example using jQuery:

// Not tested
$('iframe').each(function() {
  if ($(this).attr('href') == '') {
    // Do something with $(this).attr('longdesc')
  }
});



回答3:


While not the "cleanest" solution, another option is to use position and z-index in your CSS to "hide" an empty image under the iframe. This will give you all of the meta-data advantages of true alt text without needing to go into any complex scripting.

It's also good if you just want it as placeholder to display until the iframe is done loading.




回答4:


I don't know of a way to trap for 404 responses from an iframe in any kind of straightforward way, however you could trap it with some jQuery:

<iframe id="myFrame"></iframe>

<script>
$(function () {

  $.ajax({
     url: "http://www.abc.com",
     success: function (data) {
        $("#myFrame").html(data);
     },
     error: function () {
        $("#myFrame").html("Web site is not avaialable");
     }

});
</script>


来源:https://stackoverflow.com/questions/8252676/alternate-text-for-iframes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!