Архив

Публикации с меткой ‘javascript’
25 июня 2010 4 комментария

В примере мы изменяем ширину картинки в зависимости от размера окна и при ресайзе окна
JS:

function screenSize() {
   var w, h;
   w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
   h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
   return {w:w, h:h};
}
function ChHgh() {
   var client_width = screenSize().w;
   var content_width = client_width - 200;
   document.getElementById('imageid').style.width = content_width + 'px';
}

где 200 — это суммарная ширина других элементов рядом с картинкой
HTML:

<body onload="ChHgh();" onResize="ChHgh();">
<img id="imageid" src="/path/to/imagename.jpg" alt="imagedesc" />
</body>

Вариант второй простой и кривой:

<div style="width: 100%;"><img src="/images/m2/imagename.jpg" width="100%" /></div>
Categories: Javascript Tags:

В примере нам нужно в браузере заменять ссылки вида http://krylov.org.ua/redirect.php?http://google.ru/ на http://google.ru/
JS:

function VRmRL() {
	var finished = 0;
	while (finished <= 1) {
		var removed = "http://krylov.org.ua/redirect.php?";
		var str = document.getElementById("tmp").innerHTML;
		if (str.indexOf(removed) > -1) {
			document.getElementById("tmp").innerHTML = str.replace(removed, "");
		}
		else {
			finished = 1;
		}
	}
}

Кусок HTML как пример ну да и чтобы проверить:

<html>
<head>
<script type="text/javascript" src="rml.js"></script>
</head>
<body id="tmp" onload="VRmRL();">
<a href="http://krylov.org.ua/redirect.php?http://ya.ru/">LINK_1</a>
<br/>
<a href="http://krylov.org.ua/redirect.php?http://google.ru/">LINK_2</a>
<br/>
<a href="http://krylov.org.ua/redirect.php?http://ya.ru/">LINK_3</a>
<br/>
<a href="http://krylov.org.ua/redirect.php?http://google.ru/">LINK_4</a>
<br/>
<a href="http://google.ru/">LINK_5</a>
<br/>
<a href="http://ya.ru/">LINK_6</a>
<br/>
</body>
</html>
Categories: Javascript Tags:

1. Скачиваем дистрибутив с http://code.google.com/p/jwysiwyg/
2. Содержимое папки jwysiwyg-0.6.zip\jwysiwyg\jwysiwyg\ копируем например в /js/jwysiwyg/
3. В head (если jquery ранее не подключен, то подключаем, берем на http://jquery.com/):

<link rel='stylesheet' type='text/css' href='js/jwysiwyg/jquery.wysiwyg.css' />
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
<script type='text/javascript' src='js/jwysiwyg/jquery.wysiwyg.js'></script>
<script type='text/javascript' src='js/jwysiwyg_config.js'></script>

4. jwysiwyg_config.js (на основе wysiwyg-0.6.zip\jwysiwyg\examples\02-full.html, токльо добавлена кнопка «редактирование HTML»)

$(function()
{
$('#wysiwyg').wysiwyg({
    controls: {
      html          : { visible : true },
      strikeThrough : { visible : true },
      underline     : { visible : true },
 
      separator00 : { visible : true },
 
      justifyLeft   : { visible : true },
      justifyCenter : { visible : true },
      justifyRight  : { visible : true },
      justifyFull   : { visible : true },
 
      separator01 : { visible : true },
 
      indent  : { visible : true },
      outdent : { visible : true },
 
      separator02 : { visible : true },
 
      subscript   : { visible : true },
      superscript : { visible : true },
 
      separator03 : { visible : true },
 
      undo : { visible : true },
      redo : { visible : true },
 
      separator04 : { visible : true },
 
      insertOrderedList    : { visible : true },
      insertUnorderedList  : { visible : true },
      insertHorizontalRule : { visible : true },
 
      h4mozilla : { visible : true && $.browser.mozilla, className : 'h4', command : 'heading', arguments : ['h4'], tags : ['h4'], tooltip : "Header 4" },
      h5mozilla : { visible : true && $.browser.mozilla, className : 'h5', command : 'heading', arguments : ['h5'], tags : ['h5'], tooltip : "Header 5" },
      h6mozilla : { visible : true && $.browser.mozilla, className : 'h6', command : 'heading', arguments : ['h6'], tags : ['h6'], tooltip : "Header 6" },
 
      h4 : { visible : true && !( $.browser.mozilla ), className : 'h4', command : 'formatBlock', arguments : ['<H4>'], tags : ['h4'], tooltip : "Header 4" },
      h5 : { visible : true && !( $.browser.mozilla ), className : 'h5', command : 'formatBlock', arguments : ['<H5>'], tags : ['h5'], tooltip : "Header 5" },
      h6 : { visible : true && !( $.browser.mozilla ), className : 'h6', command : 'formatBlock', arguments : ['<H6>'], tags : ['h6'], tooltip : "Header 6" },
 
      separator07 : { visible : true },
 
      cut   : { visible : true },
      copy  : { visible : true },
      paste : { visible : true }
    }
  });
});

5. Ну и в тексте:

<div><textarea id='wysiwyg' name='some_name' cols='100' rows='20'></textarea></div>
Categories: Javascript Tags: ,
12 мая 2010 2 комментария
function screenSize() {
   var w, h; // Объявляем переменные, w - длина, h - высота
   w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
   h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
   return {w:w, h:h};
}
// Пример:
document.write(
   "Длина = " + screenSize().w + "px<br>" +
   "Высота = " + screenSize().h + "px"
);

Источник: http://webew.ru/articles/152.webew

Categories: Javascript Tags:
6 мая 2010 3 комментария

В примере изменяется высота таблицы с контентом. Предположим, что над ней есть таблица header, а под ней footer, обе талицы имеют статическую высоту по 200px каждая. В head:

function ChHgh() {
   var client_height = window.screen.height;
   var content_height = client_height - 400;
   document.getElementById('contenttable').style.height = content_height + 'px';
}

400 — высота header + высота footer

<body onload='ChHgh()'>

Где то в тексте:

<table id='contenttable'..
Categories: Javascript Tags:
30 апреля 2010 Нет комментариев

Нужен результат: меняется фон ячейки таблицы при наведении на нее мыши.
Допустим, переменная $classname может принимать значения current и nocurrent. Менять фон нужно только для nocurrent. Используем такие стили:

.nocurrent {
background: white;
}
.current {
background: red;
}
.nocurrent:hover {
background: red;
}
echo "<td class='".$classname."'>some text</td>";

В IE6 такой вариант работать не будет.
Можно так (но для current cтиль тоже будет меняться):

echo "<td class='".$classname."' onmouseover='style.backgroundColor=\"red\";' onmouseout='style.backgroundColor=\"white\";'>some text</td>";

Правильный вариант, ну во всяком случае у меня так получилось :)

function RPClass(hi) {
   if (hi.className == 'nocurrent') {
      hi.className = 'current_js';
   }
}
function RPClassR(hi) {
   if (hi.className == 'current_js') {
      hi.className = 'nocurrent';
   }
}
echo "<td class='".$classname."' onmouseover='RPClass(this);' onmouseout='RPClassR(this);'>some text</td>";

CSS (:hover теперь не нужен, стили просто будут меняться, вместо него второй стиль):

.current_js {
background: red;
}
Categories: CSS, Javascript Tags: , , ,
17 апреля 2010 1 комментарий

Использовалась Ip-камера Media Tech MT4009, смотреть которую можно только через Internet Explorer, т.к. ей нужен ActiveX. Умеет делать снимки по движению — 97 кадров, после чего перезаписывает старые файлы, т.е. текущий снимок может иметь какое угодно имя. Файлы сохраняет в папку c:\tmp\webmd, настроек чтобы изменить путь для сохранения нет. Получилось все так:
1. Расшариваем папку webmd.
2. На Web-сервере, с которого будем смотреть картинку: предположительно у нас там FreeBSD с установленным apache. Монтируем расшаренную папку. Для монтирования создаем скрипт webmd_up.sh:

#!/bin/bash
mount_smbfs -W DOMAIN_NAME -I 172.16.5.19 //username@pc_name/webmd/ /usr/home/username/public_html/remote

Для отмонтирования webmd_down.sh:

#!/bin/bash
umount /usr/home/username/public_html/remote

3. index.php:

<?php
define('PATH', 'remote/*.');
foreach (glob(PATH.'jpg') as $remote_file)
{
   $files_array[$remote_file] = filemtime($remote_file);
}
asort($files_array);
$keys = array_keys($files_array);
$selected_file = array_pop($keys);
echo "<img src='".$selected_file."?nocashe=".time()."' alt='webmd current' title='webmd' />";
?>

?nocashe=".time()." — нужно для того, чтобы отключить кэширование изображений.
4. На стрничке, где будем смотреть картинку, удобным для вас способом подключаем такой javascript:

function refresh() {
   document.all.webmd.src = document.all.webmd.src;
}
window.setInterval("refresh()", 1000);
var html = "<iframe name=\"webmd\" src=\"http://domain_name/~username/\" width=\"640px\" height=\"480px\" frameborder=\"0\" marginheight=\"0\" marginwidth=\"0\" scrolling=\"no\"></iframe>";
document.write(html);
Categories: Unix, Web Tags: , ,