w3schools上的JS HTML DOM事件

时间:2014-01-05 00:38:45

标签: javascript

我正在尝试在w3schools上学习javascript,在其中一个例子中,它有以下代码:

<html>
<body>

<div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background-    color:#D94A38;width:120px;height:20px;padding:40px;">Mouse Over Me</div>

<script>
function mOver(obj)
{
obj.innerHTML="Thank You"
}

function mOut(obj)
{
obj.innerHTML="Mouse Over Me"
}
</script>

</body>
</html> 

当您将鼠标放在块上时,它会根据需要显示谢谢。但是,如果我自己编码,那会让我感到烦恼,谢谢你不在框中。我玩弄了它,但是当你鼠标移开时我无法弄清楚如何将谢谢你放在盒子中。有可能吗?

2 个答案:

答案 0 :(得分:1)

使用CSS:text-align:center;。我还将我的JavaScript与HTML分开。我们打电话给你的第一页index.html

<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <title>Looks like your first page</title>
    <style type='text/css'>
      @import 'index.css;
    </style>
  </head>
<body class='njs'>
  <div id='whatever'>Mouse Over Me</div>
  <script type='text/javascript' src='common.js'></script>
  <script type='text/javascript' src='index.js'></script>
</body>
</html>

现在让我们将CSS页面index.css分开

#whatever{
  height:20px; width:120px; background:#D94A38; text-align:center; padding:40px;
}

现在让我们创建一个常用的JavaScript页面以供重用 - common.js

//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
  if(IE >= version){
    bod.className = className;
  }
}
function E(e){
  return doc.getElementById(e);
}
//]]>

现在,让我们创建特定于页面的JavaScript页面 - index.js

//<![CDATA[
var yourDiv = E('whatever');
yourDiv.onmouseover = function(){
  this.innerHTML = 'It Worked';
}
yourDiv.onmouseout = function(){
  this.innerHTML = 'Mouse Over Me';
}
//]]>

答案 1 :(得分:0)

使用jquery:

http://jsbin.com/ezuXupI/3/

$(document).ready(function(){ 

    var TargID = document.getElementById('bar')

       $(".foo").hover(function(){
          TargID.innerHTML="Thank You"
          $("div").css("background-color", "red");  
          $(".foo").css("text-align", "center"); 
       });

      $(".foo").mouseout(function(){
         TargID.innerHTML="Mouse Over Me"
         $("div").css("background-color", "#D94A38");  
         $(".foo").css("text-align", "left"); 

    });
});

<div class="foo" id="bar" style="background- color:#D94A38;width:220px;height:20px;padding:40px;">Mouse Over Me</div>