I have some neat code that displays one <title> for a couple seconds after loading, then replaces it with a different <title>. The effect we are trying to achieve doesn't work in some versions of Safari or on iPad, so I want to check for Safari--and if the browser is Safari, then cancel the effect. What we have at the moment does not work--I am pretty sure the problem is in the safariFix function but am still a noob and not sure what's wrong:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Uppagus</title>
<link rel="stylesheet" type="text/css" href="uppagusSTYLE.css" />
<link rel= "shortcut icon" media="all" type="image/x-icon" href="http://www.uppagus.com/favicon.ico" /> 
<link rel= "icon" media="all" type="image/vnd.microsoft.icon" href="http://uppagus.com/favicon.ico" />
<meta http-equiv="Page-Exit" content="revealTrans(Duration=2.0,Transition=23)">
<script src="jquery.min.js"></script>
<script>
  var isSafari;
  var ua = navigator.userAgent.toLowerCase(); 
  if(ua.indexOf('safari') != -1) { 
    if(ua.indexOf('chrome') > -1) {
      var isSafari = false;
    } else {
      var isSafari = true;
      safariFix();
    }
  } else {
    isSafari = false;
  }

  function safariFix() {
    $(function() {
      $('#googleFix').replaceWith('<script id="safariFix">function updateTitle() { document.getElementsByTagName("title")[0].innerHTML = "Uppagus";</script>');
    });
  }
</script>
<script id="googleFix">
function updateTitle() {
    setTimeout(function() {
        document.getElementsByTagName('title')[0].innerHTML = 'ppagus';
    }, 2000);
}
</script>

...
</head>
有帮助吗?

解决方案

Script blocks are executed top to bottom as the browser encounters them while parsing the document. So you can't use code in the first script to manipulate any elements after that script. You are trying to replace a script element that appears after.

But why try to replace the script at all? Why not just put the logic in the script:

var ua = navigator.userAgent.toLowerCase();
var isSafari = ua.indexOf('safari') != -1 && ua.indexOf('chrome') == -1;

function updateTitle() {
    if (isSafari) {
        document.getElementsByTagName("title")[0].innerHTML = "Uppagus";
    } else {
        setTimeout(function() {
            document.getElementsByTagName('title')[0].innerHTML = 'ppagus';
        }, 2000);
    }
}

(Note also that your nested if/else structure is more complicated than necessary.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top