Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > JavaScript: для новичков > Как сделать принудительный перевод каретки в <DIV>


Автор: Michael.de 10.8.2008, 01:17
Всем доброго времени суток smile
Привожу небольшой код в качестве примера:
Код

<html>
<head>
<script type="text/javascript">

function init(){
 var color = new Array('FFFFDD', 'DDFFFF', 'FFDDFF');
 var length = color.length;
 var a = new Array(length);
 var text = new Array(
  "Eclipse is an open source community, whose projects are focused on building an open development platform comprised of extensible frameworks, tools and runtimes for building, deploying and managing software across the lifecycle. The Eclipse Foundation is a not-for-profit, member supported corporation that hosts the Eclipse projects and helps cultivate both an open source community and an ecosystem of complementary products and services.",
  "The Eclipse Project was originally created by IBM in November 2001 and supported by a consortium of software vendors. The Eclipse Foundation was created in January 2004 as an independent not-for-profit corporation to act as the steward of the Eclipse community. The independent not-for-profit corporation was created to allow a vendor neutral and open, transparent community to be established around Eclipse. Today, the Eclipse community consists of individuals and organizations from a cross section of the software industry.",
  "The Eclipse Foundation is funded by annual dues from our members and governed by a Board of Directors. Strategic Developers and Strategic Consumers hold seats on this Board, as do representatives elected by Add-in Providers and Open Source committers. The Foundation employs a full-time professional staff to provide services to the community but does not employ the open source developers, called committers, which actually work on the Eclipse projects. Eclipse committers are typically employed by organizations or are independent developers that volunteer their time to work on an open source project."
 );
 var e = 'px';
 for (var i=0; i<length; i++){
  a[i] = document.createElement('div');
  a[i].style.position = 'absolute';
  a[i].style.left = 20+300*i+e;
  a[i].style.top = 20+e;
  a[i].style.width = 300+e;
  a[i].style.height = 300+e;
  a[i].style.backgroundColor = color[i];
  a[i].appendChild(document.createTextNode(text[i]));
  a[i].onclick = show;
  document.body.appendChild(a[i]);
 }
}

function show() {alert(this.style.left);}// this.value ???

</script>
</head>
<body onload='init();'>
</body>
</html>

Вопрос: Как мне осуществить перевод каретки на новую строку? Пробовал <br> и \n - не работают (а \t - только в MS IE) ???
Доп. вопросик: в 23 строке я "запихнул" текст в DIV. А как мне его вывести алертом в show()? this.value не пашет smile
P.S. Доп. вопросик отпадает (пашет с this.childNodes[0].nodeValue), остаётся Вопрос. И что парадоксально - alert() чётко отображает всё \n и \t  smile

Автор: bars80080 10.8.2008, 09:17
а \r\n ?

а это что такое for (var i=0; i<length; i++){

кстати, а если добавлять текст не как createTextNode , а в качестве html аналога? тогда должно заработать <br />

Автор: ksnk 10.8.2008, 10:21
Дык! bars80080 дело говорит smile Нужно в массиве хранить html разметку с <br>. а alert'ом пользоваться примерно так:


Код

// 23 строка - меняем на 
  a[i].innerHTML=text[i];
...

// этакий strip_tags
function show() {
    alert(
        this.innerHTML.replace(/<br\s*\/?>/i,'\n').replace(/<.*?>/gi,'')
    ) ;
}

 

Автор: Michael.de 10.8.2008, 13:32
Цитата(bars80080 @  10.8.2008,  09:17 Найти цитируемый пост)
а \r\n ?

а это что такое for (var i=0; i<length; i++){
...
\r\n работает только в MS IE... и как табуляция smile  FF это игнорирует.
Переменную length я определил в 7 строке smile

Цитата(ksnk @  10.8.2008,  10:21 Найти цитируемый пост)
...Нужно в массиве хранить html разметку с <br>...
Не совсем понял... это как?

Автор: ksnk 10.8.2008, 13:42
Цитата(Michael.de @  10.8.2008,  13:32 Найти цитируемый пост)
Не совсем понял... это как?

Примерно так:
Код

var text = new Array(
  'Eclipse <img style="float:left" src="eclipse.gif"> is an open source community,<br/> who...


Автор: bars80080 10.8.2008, 13:44
Цитата(Michael.de @  10.8.2008,  13:32 Найти цитируемый пост)
Не совсем понял... это как?

так ksnk, пример привёл

вместо твоего document.createTextNode(text[i]) добавить в созданный блок хтмл-текст (т.е. твой текст с <br />) присвоить с помощью .innerHTML = 'твой <br />текст';

Автор: Michael.de 10.8.2008, 21:04
ksnk, bars80080: да, с innerHTML работает smile Жалко, что не получилось по DOM-у :/
Спасибо! smile

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)