簡體   English   中英

在鼠標懸停標題上更改文本顏色

[英]Change text color on mouseover caption

我正在嘗試建立一個頁面,其中連續有多個標題,下面是描述性段落。 當用戶在標題上滾動時,段落將根據他們懸停的標題進行更改。 我希望每個標題使用不同的顏色,並且段落的字體顏色應更改為與標題的顏色匹配。 我遇到的問題是更改段落的顏色。

這是我的示例:

<script type="text/javascript">
function onover(caption)
{document.getElementById('text').innerHTML=caption;}
{document.getElementById('text2').innerHTML=caption;}
</script>

<a onmouseover="onover('Paragraph 1')" style="color:green">Title 1</a>
<a onmouseover="onover('Paragraph 2')" style="color:red">Title 2</a>
</br>
<div id="text" style="color:green">Paragraph 1</div>
<div id="text2" style="color:red"></div>

更新由於OP希望替換文本,

<script type="text/javascript">
       function onover(caption,color) {
          document.getElementById('text').innerHTML=caption;
          document.getElementById('text').style.color=color;
          document.getElementById('text2').style.color=color;
   } 
</script>

<a onmouseover="onover('Paragraph 1','green')" style="color:green" id='one'>Title 1</a>
<a onmouseover="onover('Paragraph 2','red')" style="color:red">Title 2</a>
</br>
<div id="text" style="color:green">Paragraph 1</div>

演示

更新2

<script type="text/javascript">
function onover(caption, objId, obj)
{
   document.getElementById(objId).innerHTML=caption;
   document.getElementById(objId).style.color = obj.style.color;
}
</script>

<a onmouseover="onover('Paragraph 1', 'text', this)" style="color:green">Title 1</a>
<a onmouseover="onover('Paragraph 2', 'text2', this)" style="color:red">Title 2</a>
</br>
<div id="text" style="color:green">Paragraph 1</div>
<div id="text2" style="color:red"></div>
document.getElementById('text2').style.color = 'blue';

會改變文本的顏色。

在單獨的注釋上, {document.getElementById('text2').innerHTML=caption;}不是onover函數的一部分。

我強烈建議您將樣式,邏輯和內容分開。 它使您的代碼更易於閱讀和維護。 一些建議:

  • 所有內聯樣式(例如)都應替換為樣式表
    • 在此示例中,這樣做允許您對菜單項和段落重復使用相同的樣式
  • 利用jQuery之類的第三方JavaScript庫簡化跨瀏覽器javascript實現不一致的處理
  • 以編程方式附加事件,而不是內聯
  • 不要試圖單獨處理每種情況; 多抽象一些代碼。 無需創建多個div即可使樣式匹配
  • 一般來說,將所有腳本內容放在頁面的末尾,緊接在結束body標簽之前是個好主意。 這將使您的內容在頁面處理javascript時可見,並使網站的加載速度更快

這是如何實施這些建議的示例:

<style>
  .red { color: red; }
  .green { color: green; }
</style>
<div id="TitleBar">
  <a data-text="Paragraph 1" class="green">Title 1</a>
  <a data-text="Paragraph 2" class="red">Title 2</a>
</div>
<div id="text"></div>
<script src="http://code.jquery.com/jquery-git.js"></script>
<script>
  $('#TitleBar').on('hover', 'a', function (e) {
    var $evTarg = $(e.target),
        $dest = $('#text');
    $dest.html($evTarg.data('text')).attr('class', $evTarg.attr('class'));
  });
</script>

**最后一個注釋-如果“ Paragraph x”文本超過幾個單詞,請考慮將文本存儲在命名數組中,而不是將其嵌入到源標簽中。

您最好通過CSS做到這一點。 完全不需要編程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM