2014-11-14 7 views
1

у меня есть: Простой блок HTML текста:Javascript: Переключить текст на выберите

<p> 
The future of manned space exploration and development of space depends critically on the 
creation of a dramatically more proficient propulsion architecture for in-space transportation. 
A very persuasive reason for investigating the applicability of nuclear power in rockets is the 
vast energy density gain of nuclear fuel when compared to chemical combustion energy... 
</p> 

Вопрос:Как вставить понятие НИЖЕ (между существующими строками текста) некоторой фразы с помощью JavaScript?

I.e. Я хочу в нескольких словах пояснить, что такое nuclear power по тексту выше, поэтому я хочу вставить несколько слов ниже этой фразы (скажем, на мышь).

+0

Должен ли он иметь чистый JavaScript? Почему вы не можете пометить фразу в HTML? – RoToRa

+0

@RoToRa потому что я хочу сделать это динамически на некоторых событиях –

ответ

2

Это сделает это. Пожалуйста, дайте мне знать, если вам нужна дополнительная информация.

<!DOCTYPE html> 
<html> 

<head></head> 

<body> 
<p> 
The future of manned space exploration and development of space depends critically on the 
creation of a dramatically more proficient propulsion architecture for in-space transportation. 
A very persuasive reason for investigating the applicability of nuclear power in rockets is the 
vast energy density gain of nuclear fuel when compared to chemical combustion energy... 
</p> 
<script> 

var p = document.getElementsByTagName('p'); 
p = p[0]; 
var tmp = ''; 
p.addEventListener('mouseover', function(){ 
    tmp = p.innerHTML; 
    p.innerHTML = p.innerHTML + ' ...about nuclear...'; 
}, false); 

p.addEventListener('mouseout', function(){ 
    p.innerHTML = tmp; 
}, false); 
</script> 

</body> 

</html> 

Вот версия с общей функцией, которую вы можете использовать для любого элемента.

<!DOCTYPE html> 
<html> 

<head> 
<script> 

var switchText = function(element, text){ 
    var tmp = ''; 
    element.addEventListener('mouseover', function(){ 
     tmp = element.innerHTML; 
     element.innerHTML = element.innerHTML + text; 
    }, false); 

    element.addEventListener('mouseout', function(){ 
     element.innerHTML = tmp; 
    }, false); 
}; 
</script> 
</head> 

<body> 
<p> 
The future of manned space exploration and development of space depends critically on the 
creation of a dramatically more proficient propulsion architecture for in-space transportation. 
A very persuasive reason for investigating the applicability of nuclear power in rockets is the 
vast energy density gain of nuclear fuel when compared to chemical combustion energy... 
</p> 
<script> 

var p = document.getElementsByTagName('p'); 
switchText(p[0], '...about nuclear...'); 

</script> 

</body> 

</html> 

Вставить его рядом со словом. Я использовал теги span с красным цветом для выделения. Вы можете, конечно, добавить, что захотите.

<!DOCTYPE html> 
<html> 

<head> 
<script> 

var switchText = function(element, words, text){ 
    var tmp = ''; 
    element.addEventListener('mouseover', function(){ 
     tmp = element.innerHTML; 
     element.innerHTML = element.innerHTML.replace(words, function(m){ 
      return m+'<span class="nuc">'+text+'</span>'; 

     }); 
    }, false); 

    element.addEventListener('mouseout', function(){ 
     element.innerHTML = tmp; 
    }, false); 
}; 
</script> 
<style> 
.nuc{ color: red; } 
</style> 
</head> 

<body> 
<p> 
The future of manned space exploration and development of space depends critically on the 
creation of a dramatically more proficient propulsion architecture for in-space transportation. 
A very persuasive reason for investigating the applicability of nuclear power in rockets is the 
vast energy density gain of nuclear fuel when compared to chemical combustion energy... 
</p> 
<script> 

var p = document.getElementsByTagName('p'); 
switchText(p[0], /nuclear/g, '...about nuclear...'); 

</script> 

</body> 

</html> 

Я также добавил параметр слова функции switchText, чтобы сделать его более универсальным, а также.

Четвертое, и окончательное условие разрешено. Следующее позволит текст на специально зависающем слове или фразе.

<!DOCTYPE html> 
<html> 

<head> 
<script> 

var switchText = function(element, words, text){ 

    element.innerHTML = element.innerHTML.replace(words, function(m){ 
     return '<p class="nuc">'+m+'</p>'; 


    }); 

    var nuc = element.getElementsByClassName('nuc'); 
    for(var i=0; i<nuc.length; i++){ 
     (function(nuc){ 
      var tmp = nuc.innerHTML, 
       doing = false; 
      nuc.addEventListener('mouseover', function(){ 
       if(!doing) 
        this.innerHTML = this.innerHTML + text; 

       doing = true; 
      }); 

      nuc.addEventListener('mouseout', function(){ 
       this.innerHTML = tmp; 
       doing = false; 
      }); 
     })(nuc[i]); 
    } 
}; 
</script> 
<style> 
.nuc{ color: red; display: inline;} 
</style> 
</head> 

<body> 
<p> 
The future of manned space exploration and development of space depends critically on the 
creation of a dramatically more proficient propulsion architecture for in-space transportation. 
A very persuasive reason for investigating the applicability of nuclear power in rockets is the 
vast energy density gain of nuclear fuel when compared to chemical combustion energy... 
</p> 
<script> 

var p = document.getElementsByTagName('p'); 
switchText(p[0], /nuclear/g, '...about nuclear...'); 

</script> 

</body> 

</html> 

В качестве напоминания, используя этот метод с некоторыми типами CSS positioning можно сделать styled popups, inline navigation, и, возможно, другие коробки с странным поведением.

+0

извините, если я объясню задачу плохо, но мне нужно вставить «... о ядерном ...» текст НИЖЕ ядерное слово. Я имею в виду между существующими строками текста –

+0

Хотите ли вы встроить внутри абзаца? –

+0

да, я хочу встроить его –

Смежные вопросы