Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 18.03.2013, 21:21
Кандидат Javascript-наук
Отправить личное сообщение для mitiya Посмотреть профиль Найти все сообщения от mitiya
 
Регистрация: 13.01.2011
Сообщений: 114

как получить тот кусок текста который сейчас видно на экране ?
есть большой текст. весь он не помещается на экран.
мне нужно получить в переменную только тот кусов который сейчас видно.
Ума не приложу как это сделать (
Ответить с цитированием
  #2 (permalink)  
Старый 18.03.2013, 21:42
Аватар для megaupload
Профессор
Отправить личное сообщение для megaupload Посмотреть профиль Найти все сообщения от megaupload
 
Регистрация: 18.01.2013
Сообщений: 1,098

блин есть способ но надо чтобы ты разбирался потому что там чуть што ни так то ты сразу не поймешь
Ответить с цитированием
  #3 (permalink)  
Старый 18.03.2013, 21:43
Аватар для megaupload
Профессор
Отправить личное сообщение для megaupload Посмотреть профиль Найти все сообщения от megaupload
 
Регистрация: 18.01.2013
Сообщений: 1,098

посчитай прокрутку элемента с текстом посчитай размер шрифта и.т.п.
размер экрана, перносы строк и.т.п.


а вообще я не знаю как это сделать
Ответить с цитированием
  #4 (permalink)  
Старый 18.03.2013, 22:23
Кандидат Javascript-наук
Отправить личное сообщение для mitiya Посмотреть профиль Найти все сообщения от mitiya
 
Регистрация: 13.01.2011
Сообщений: 114

прокрутка и шрифт не пойдет. мало того что в разных браузерах все несколько по разному, дак еще и на большом тексте мне кажется ошибка накопится большая.
Ответить с цитированием
  #5 (permalink)  
Старый 18.03.2013, 22:26
Аватар для megaupload
Профессор
Отправить личное сообщение для megaupload Посмотреть профиль Найти все сообщения от megaupload
 
Регистрация: 18.01.2013
Сообщений: 1,098

даже не знаю как те помочь а зачем вообще такая задача?
Ответить с цитированием
  #6 (permalink)  
Старый 19.03.2013, 00:45
Кандидат Javascript-наук
Отправить личное сообщение для mitiya Посмотреть профиль Найти все сообщения от mitiya
 
Регистрация: 13.01.2011
Сообщений: 114

вот тут описано примерно то что мне нужно. Но оно не совсем работает. Нормально работает если текст видно сначала, но если его промотать то работает не правильно.
Ответить с цитированием
  #7 (permalink)  
Старый 19.03.2013, 01:28
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

крутим кликаем по тексту )))
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title> - jsFiddle demo</title>

  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">


  <link rel="stylesheet" type="text/css" href="/css/result-light.css">

  <style type='text/css'>
    .textnode {
    padding:1px;
    margin:0 1px;
    height:16px;
    float:left;
}
  </style>



<script type='text/javascript'>
$(window).load(function(){
$(function(){
    var tmp_id = 1;
    $('body div').contents().each(function(){
        if(this.nodeType == 3)
        {
            var _this = $(this);
            var _swap = $('<div id="textnodewrapper' + tmp_id + '" />');
            $.each(_this.text().split(' '),function(i,val){
                if($.trim(val).length > 0)
                {
                    _swap.append('<span class="textnode">' + val + '</span>');
                }
            });
            _swap.insertBefore(_this);
            _this.remove();
        }
        tmp_id++;
    });
    $('body').click(function(){
    var screen_bottom = $(window).height();
    var screen_scroll = $(window).scrollTop();
    var on_screen_words = [];
    $('.textnode').each(function(){
        if(($(this).position().top + $(this).height()) < (screen_bottom+screen_scroll)&& $(this).position().top>(screen_scroll-$(this).height()))
        {
            on_screen_words.push($(this).text());
        }
    });
    alert(on_screen_words.join(' '));

    })

});
});
</script>


</head>
<body>
  <div>

    "Call me Ishmael," Moby-Dick begins, in one of the most recognizable opening lines in English-language literature. The narrator, an observant young man setting out from Manhattan, has experience in the merchant marine but has recently decided his next voyage will be on a whaling ship. On a cold, gloomy night in December, he arrives at the Spouter-Inn in New Bedford, Massachusetts, and agrees to share a bed with a then-absent stranger. When his bunk mate, a heavily tattooed Polynesian harpooner named Queequeg, returns very late and discovers Ishmael beneath his covers, both men are alarmed, but the two quickly become close friends and decide to sail together from Nantucket, Massachusetts on a whaling voyage.
In Nantucket, the pair signs on with the Pequod, a whaling ship that is soon to leave port. The ship’s captain, Ahab, is nowhere to be seen; nevertheless, they are told of him — a "grand, ungodly, godlike man,"[26] who has "been in colleges as well as 'mong the cannibals," according to one of the owners. The two friends encounter a mysterious man named Elijah on the dock after they sign their papers and he hints at troubles to come with Ahab. The mystery grows on Christmas morning when Ishmael spots dark figures in the mist, apparently boarding the Pequod shortly before it sets sail that day.
The ship’s officers direct the early voyage while Ahab stays in his cabin. The chief mate is Starbuck, a serious, sincere Quaker and fine leader; second mate is Stubb, happy-go-lucky and cheerful and always smoking his pipe; the third mate is Flask, short and stout but thoroughly reliable. Each mate is responsible for a whaling boat, and each whaling boat of the Pequod has its own pagan harpooneer assigned to it. Some time after sailing, Ahab finally appears on the quarter-deck one morning, an imposing, frightening figure whose haunted visage sends shivers over the narrator.
“    He looked like a man cut away from the stake, when the fire has overrunningly wasted all the limbs without consuming them, or taking away one particle from their compacted aged robustness... Threading its way out from among his grey hairs, and continuing right down one side of his tawny scorched face and neck, till it disappeared in his clothing, you saw a slender rod-like mark, lividly whitish. It resembled that perpendicular seam sometimes made in the straight, lofty trunk of a great tree, when the upper lightning tearingly darts down it, and without wrenching a single twig, peels and grooves out the bark from top to bottom ere running off into the soil, leaving the tree still greenly alive, but branded.    ”
One of his legs is missing from the knee down and has been replaced by a prosthesis fashioned from a sperm whale's jawbone.
Soon gathering the crewmen together, with a rousing speech Ahab secures their support for his single, secret purpose for this voyage: hunting down and killing Moby Dick, an old, very large sperm whale, with a snow-white hump and mottled skin, that crippled Ahab on his last whaling voyage. Only Starbuck shows any sign of resistance to the charismatic but monomaniacal captain. The first mate argues repeatedly that the ship’s purpose should be to hunt whales for their oil, with luck returning home profitably, safely, and quickly, but not to seek out and kill Moby Dick in particular — and especially not for revenge. Eventually even Starbuck acquiesces to Ahab's will, though harboring misgivings.
The mystery of the dark figures seen before the Pequod set sail is explained during the voyage's first lowering for whales. Ahab has secretly brought along his own boat crew, including a mysterious harpooneer named Fedallah (also referred to as 'the Parsee'), an inscrutable figure with a sinister influence over Ahab. Later, while watching one night over a captured whale carcass, Fedallah gives dark prophecies to Ahab regarding their twin deaths.


Moby Dick
The novel describes numerous "gams," social meetings of two ships on the open sea. Crews normally visit each other during a gam, captains on one vessel and chief mates on the other. Mail may be exchanged and the men talk of whale sightings or other news. For Ahab, however, there is but one relevant question to ask of another ship: “Hast seen the White Whale?” After meeting several other whaling ships, which have their own peculiar stories, the Pequod enters the Pacific Ocean. Queequeg becomes deathly ill and requests that a coffin be built for him by the ship’s carpenter. Just as everyone has given up hope, Queequeg changes his mind, deciding to live after all, and recovers quickly. His coffin becomes his sea chest, and is later caulked and pitched to replace the Pequod's life buoy.
Soon word is heard from other whalers of Moby Dick. The jolly Captain Boomer of the Samuel Enderby has lost an arm to the whale, and is stunned at Ahab's burning need for revenge. Next they meet the Rachel, which has seen Moby Dick very recently. As a result of the encounter, one of its boats is missing; the captain’s youngest son had been aboard. The Rachel's captain begs Ahab to aid in the search for the missing boat, but Ahab is resolute; the Pequod is very near the White Whale now and will not stop to help. Finally the Delight is met, even as its captain buries a sailor who had been killed by Moby Dick. Starbuck begs Ahab one final time to reconsider his thirst for vengeance, but to no avail.
The next day, the Pequod meets Moby Dick. For two days, the Pequod's crew pursues the whale, which wreaks widespread destruction, including the disappearance of Fedallah. On the third day, Moby Dick rises up to reveal Fedallah tied to him by harpoon ropes, clearly dead. Even after the initial battle on the third day, as Moby Dick swims away from the Pequod, Starbuck exhorts Ahab one last time to desist, observing that "Moby-Dick seeks thee not. It is thou, thou, that madly seekest him!"
Ahab ignores this voice of reason and continues with his ill-fated chase. As the three boats sail out to hunt him, Moby Dick damages two of them, forcing them to go back to the ship and leaving only Ahab's vessel intact. Ahab harpoons the whale, but the harpoon-line breaks. Moby Dick then rams the Pequod itself, which begins to sink. As Ahab harpoons the whale again, the unfolding harpoon-line catches him around his neck and he is dragged into the depths of the sea by the diving Moby Dick. The boat is caught up in the whirlpool of the sinking ship, which takes almost all the crew to their deaths. Only Ishmael survives, clinging to Queequeg’s coffin-turned-life buoy for an entire day and night before the Rachel rescues him.

</div>

</body>


</html>
Ответить с цитированием
  #8 (permalink)  
Старый 19.03.2013, 01:42
Кандидат Javascript-наук
Отправить личное сообщение для mitiya Посмотреть профиль Найти все сообщения от mitiya
 
Регистрация: 13.01.2011
Сообщений: 114

хм. Вроде как работает. Не могли бы вы пояснить что там происходит ?
Ответить с цитированием
  #9 (permalink)  
Старый 19.03.2013, 01:50
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,064

mitiya,
текст разбивается на блоки -- если блок входит в видимый диапазон - позиция больше скрола но меньше (скрол + высота окна) - набирается массив подходящих под это условие
Ответить с цитированием
  #10 (permalink)  
Старый 19.03.2013, 06:58
Аватар для danik.js
Профессор
Отправить личное сообщение для danik.js Посмотреть профиль Найти все сообщения от danik.js
 
Регистрация: 11.09.2010
Сообщений: 8,804

рони, прикольно. Следует понимать, что не стоит использовать это на больших объемах текста, иначе все будет тормозить.
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как вытянуть кусок текста из адреса? GuitarFan Events/DOM/Window 3 30.09.2012 19:20
пытаюсь заменить часть текста в html который вроде как в переменной. mitiya Общие вопросы Javascript 4 22.03.2012 18:16