Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Em funcionamento: http://hunternh.110mb.com/exemplos/popup.html
popup.js
/**************************************** Popup v1.0 ** Autor: Wagner B. Soares ****************************************/Popup = function(oRoot, width, height, minX, maxX, minY, maxY){ var popup = new Object(); var id = oRoot; // recebe a div que será a popup var win = document.getElementById(id); // div que é utilizada para minimizar e maximizar var animate = jQuery.create("div",{},[]); // container do conteúdo var container = jQuery.create("div",{"class":"container-window"},[]); // cabeçalho da popup var header = jQuery.create("span",{"class":"window-header"},[]); // texto do cabeçalho var headerText = null; width = (isNumber(width) && width > 200)? width: 200; height = (isNumber(height) && height > 200)? height: 200; var images = new Array(new Image(),new Image()); images[0].src = "button-close.gif"; images[1].src = "button-min.gif"; //cria e configura o botão minimizar var buttonMin = jQuery.create("img",{"id":"minimize-"+id,"alt":"","title":"","src":images[1].src},[]); buttonMin.onclick = function() { jQuery(animate).animate({height:"toggle"},"slow"); } //cria e configura o botão fechar var buttonClose = jQuery.create("img",{"id":"close-"+id,"alt":"","title":"","src":images[0].src},[]); buttonClose.onclick = function() { jQuery(win).animate({opacity:"hide"},"slow"); } // cria o container dos botões var buttonContainer = jQuery.create("span",{"class":"window-buttons"},[]); jQuery(buttonContainer).append(buttonMin); jQuery(buttonContainer).append(buttonClose); jQuery(container).html(jQuery(win).html()); jQuery(win).empty(); jQuery(win).append(buttonContainer); jQuery(win).append(header); jQuery(animate).append(container); jQuery(win).append(animate); jQuery(win).css({"width":(width+"px"),"border":"1px solid","padding": "0px","position": "absolute","text-align": "center","background-color":"#C0C0C0","display":"none"}); jQuery(header).css({"display": "block","margin": "0px","padding": "0px","padding-left": "5px","left":"0px","line-height": "22px","text-align": "left","width":((width-5)+"px"),"height":(22+"px"),"color": "#FFFFFF","font-weight": "bold","background-color": "#000000"}); jQuery(buttonContainer).css({"display": "block","cursor": "move","margin": "0px","position": "absolute","left":"0px","text-align": "right","line-height": "22px","width":((width-2)+"px"),"height":(22+"px")}); jQuery("img",buttonContainer).css({"margin-right": "2px","cursor": "pointer","width": "23px","height": "23px"}); jQuery(container).css({"margin":"3px","width":((width-8)+"px"),"height":((height-29)+"px"),"text-align": "left","overflow":"auto","background-color":"#FFFFFF","border":"1px solid"}); // função para configurar o texto do cabeçalho da popup this.setTitle = function(t) { headerText = document.createTextNode(t); jQuery(header).append(headerText); }; popup.getPageSize = function() { var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight arrayPageSize = new Array(w,h) return arrayPageSize; }; popup.position = function() { var pagesize = popup.getPageSize(); jQuery(win).css({left: ((pagesize[0] - width)/2), top: ((pagesize[1]-height)/2) }); }; // exibe a popup this.show = function() { popup.position(); jQuery(win).animate({opacity:"show"},"slow"); }; var Drag = { obj : null, init : function(oRoot,head, minX, maxX, minY, maxY) { var o = head; o.onmousedown = Drag.start; o.root = oRoot; if (isNaN(parseInt(o.root.style.left ))) o.root.style.left = "0px"; if (isNaN(parseInt(o.root.style.top ))) o.root.style.top = "0px"; o.minX = typeof minX != 'undefined' ? minX : null; o.minY = typeof minY != 'undefined' ? minY : null; o.maxX = typeof maxX != 'undefined' ? maxX : null; o.maxY = typeof maxY != 'undefined' ? maxY : null; o.root.onDragStart = new Function(); o.root.onDragEnd = new Function(); o.root.onDrag = new Function(); }, start : function(e) { var o = Drag.obj = this; e = Drag.fixE(e); o.root.style.zIndex = "200"; var y = parseInt(o.root.style.top); var x = parseInt(o.root.style.left); o.root.onDragStart(x, y); o.lastMouseX = e.clientX; o.lastMouseY = e.clientY; if (o.minX != null) o.minMouseX = e.clientX - x + o.minX; if (o.maxX != null) o.maxMouseX = o.minMouseX + o.maxX - o.minX; if (o.minY != null) o.minMouseY = e.clientY - y + o.minY; if (o.maxY != null) o.maxMouseY = o.minMouseY + o.maxY - o.minY; document.onmousemove = Drag.drag; document.onmouseup = Drag.end; return false; }, drag : function(e) { e = Drag.fixE(e); var o = Drag.obj; var ey = e.clientY; var ex = e.clientX; var y = parseInt(o.root.style.top); var x = parseInt(o.root.style.left); var nx, ny; if (o.minX != null) ex = Math.max(ex, o.minMouseX); if (o.maxX != null) ex = Math.min(ex, o.maxMouseX); if (o.minY != null) ey = Math.max(ey, o.minMouseY); if (o.maxY != null) ey = Math.min(ey, o.maxMouseY); nx = x + ((ex - o.lastMouseX) * 1); ny = y + ((ey - o.lastMouseY) * 1); Drag.obj.root.style["left"] = nx + "px"; Drag.obj.root.style["top"] = ny + "px"; Drag.obj.lastMouseX = ex; Drag.obj.lastMouseY = ey; Drag.obj.root.onDrag(nx, ny); return false; }, end : function() { document.onmousemove = null; document.onmouseup = null; Drag.obj.root.onDragEnd( parseInt(Drag.obj.root.style["left"]), parseInt(Drag.obj.root.style["top"])); Drag.obj.root.style.zIndex = "199"; Drag.obj = null; }, fixE : function(e) { if (typeof e == 'undefined') e = window.event; if (typeof e.layerX == 'undefined') e.layerX = e.offsetX; if (typeof e.layerY == 'undefined') e.layerY = e.offsetY; return e; } }; // inicializa a popup this.init = function() { popup.position(); Drag.init(win,buttonContainer, minX, maxX, minY, maxY); };};Eu fiz para manter o estado, se quiser posso passar como fazer para que apareca aberto.
Oi.
Pode me ajudar dando a chamada da função que voce usou no seu popup de exemplo, com os valores passados nos parametros?
Parabens pelo codigo!! está divino http://forum.imasters.com.br/public/style_emoticons/default/thumbsup.gif
São necessários esses arquivos:
http://hunternh.110mb.com/exemplos/jquery-latest.pack.js
http://hunternh.110mb.com/exemplos/jquery-dom.js
http://hunternh.110mb.com/exemplos/tipos.js
http://hunternh.110mb.com/exemplos/popup.js
Para usar é o seguinte, você precisa criar uma div que será a popup e dentro dela coloque o conteúdo:
<div id="popup"> <!-- div que será a popup --> <div class="conteudo"> Teste<br /> lçkjhaljkçsdljfçasdfhjqkwuherqiuwheruihqwiehrqiouwehrouiqwyeuryuiqweroyquwiyruqwe<br /> lçkjhaljkçsdljfçasdfhj<br /> lçkjhaljkçsdljfçasdfhj<br /> lçkjhaljkçsdljfçasdfhj<br /> lçkjhaljkçsdljfçasdfhj<br /> lçkjhaljkçsdljfçasdfhj<br /> </div> </div>Abaixo da div você coloca esse código que é o do exemplo:
<script type="text/javascript"> //<![CDATA[ var popup = new Popup("popup",300,300); //aqui cria a popup popup.setTitle("Teste"); //aqui configura o título da popup popup.init(); //aqui inicia a popup //]]> </script>E para mostrar a popup você chama através de um link ou botão como abaixo:
<a href="#" onclick="popup.show();">Exibir popup</a>tem como esse pop-up ser modal?
Obrigado! http://forum.imasters.com.br/public/style_emoticons/default/clap.gif
boa tardes pessoal, para já quero-vos felicitar pelo belo forum que aqui têm :)...um Olá de Portugal... depois queria agradecer ao hunternh por este script que me ajudou mto num efeito que eu quis por na minh homepage.. só queria perguntar uma coisa ao hunternh...é que eu tenho uma animação flash a correr na HP onde abro o DIV, e o DIV fica por baixo dessa animação...há alguma forma de por o DIV por cima ?cumprimentos,Bleeding_me
ora, como ainda não obtive resposta, tive de resolver o problema de outra maneira. O problema está mesmo no FLASH, ora peguei e transformei o flash em imagen's e depois com script em javascript coloquei um fade entre imagens..cumpz,Bleeding_me
o flash tem um parâmetro chamado wmode onde deve ser defino o valor "transparent"
brigadão hunterh, agora sim,funcionou, ja posso tirar assim mais um script la da pagina.. quando ela tiver pronta eu posto aqui o link dela.
Link para download dos arquivos: http://rapidshare.com/files/84010206/popup.rar.html
Link para download dos arquivos: http://rapidshare.com/files/84010206/popup.rar.html
Valeu!!! ajudou muitoooo http://forum.imasters.com.br/public/style_emoticons/default/clap.gif
Eu to com um problema nas imagens... primeiro q elas não parecem, depois elas não querem funcionar... quer dizer, a janela não fecha nem minimiza...
Aqui o código da página:
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="[http://www.w3.org/1999/xhtml"](http://www.w3.org/1999/xhtml) xml:lang="pt-br" lang="pt-br">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="Wagner B. Soares" />
<title>Popup</title>
<style type="text/css">
body
{
font-size: 11px;
font-family: Verdana, Arial, Helvetica, Garamond, sans-serif, serif;
}
.conteudo
{
margin: 0px;
}
</style>
<script type="text/javascript" src="others\jquery-latest.pack.js"></script>
<script type="text/javascript" src="others\jquery-dom.js"></script>
<script type="text/javascript" src="others\tipos.js"></script>
<script type="text/javascript" src="others\popup2.js"></script>
</head>
<body>
<div id="popup">
<div class="conteudo">
<object width='780' height='445'>
<param name='movie' value='http://br.youtube.com/cp/vjVQa1PpcFO225htNg2V2ppn-0Q4huFKX6fKyH5ye6Y='></param>
<param name='wmode' value='transparent'></params>
<embed src='http://br.youtube.com/cp/vjVQa1PpcFO225htNg2V2ppn-0Q4huFKX6fKyH5ye6Y=' type='application/x-shockwave-flash' wmode='transparent' width='780' height='445'></embed>
</object>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
var popup = new Popup("popup",800,470);
popup.setTitle("Evolução do Surf");
popup.init();
//]]>
</script>
<a href="#" onclick="popup.show();"><img src="images\surfhavai.bmp" border="0"></a>
</body>
</html>
Abraços
Edit: descobri que as imagens não apareciam pois coloquei na pasta errada, mas descobri também q elas param de funcionar quando eu aumento o tamanho da janela popup... tem algum jeito de concertar isso?? Abraços!
E outra dúvida q surgiu agora: eu tenho como criar outra div id pra ser tipo uma "Popoup2", para que eu possa colocar duas destas janelas na mesma página?
Quer dizer, como uma div id é única, eu não posso fazer duas popups na mesma página, a não ser que eu faça duas divs id... eu sou meio iniciante e não sei se é isso msm, mas acho q é, né? E depois, eu não sie onde criar outra div... (copiar o conteúdo da "popup" e colar numa outra id, tipo a "popup2")
Abraços,
espero a reposta...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="[http://www.w3.org/1999/xhtml"](http://www.w3.org/1999/xhtml) xml:lang="pt-br" lang="pt-br">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="Wagner B. Soares" />
<title>Popup</title>
<style type="text/css">
body
{
font-size: 11px;
font-family: Verdana, Arial, Helvetica, Garamond, sans-serif, serif;
}
.conteudo
{
margin: 5px;
}
</style>
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery-dom.js"></script>
<script type="text/javascript" src="tipos.js"></script>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div id="popup">
<div class="conteudo">
Teste<br />
lçkjhaljkçsdljfçasdfhjqkwuherqiuwheruihqwiehrqiouwehrouiqwyeuryuiqweroyquwi
eyruqwe<br />
lçkjhaljkçsdljfçasdfhj<br />
lçkjhaljkçsdljfçasdfhj<br />
lçkjhaljkçsdljfçasdfhj<br />
lçkjhaljkçsdljfçasdfhj<br />
lçkjhaljkçsdljfçasdfhj<br />
</div>
</div>
<script type="text/javascript">
//<![CDATA[
var popup = new Popup("popup",300,300);
popup.setTitle("Teste");
popup.init();
//]]>
</script>
<a href="#" onclick="popup.show();">Exibir popup</a>
<div id="popup2">
<div class="conteudo">
Teste<br />
lçkjhaljkçsdljfçasdfhjqkwuherqiuwheruihqwiehrqiouwehrouiqwyeuryuiqweroyquwi
eyruqwe<br />
lçkjhaljkçsdljfçasdfhj<br />
lçkjhaljkçsdljfçasdfhj<br />
lçkjhaljkçsdljfçasdfhj<br />
lçkjhaljkçsdljfçasdfhj<br />
lçkjhaljkçsdljfçasdfhj<br />
</div>
</div>
<script type="text/javascript">
//<![CDATA[
var popup2 = new Popup("popup2",500,500);
popup2.setTitle("Teste");
popup2.init();
//]]>
</script>
<a href="#" onclick="popup2.show();">Exibir popup</a>
</body>
</html>Ah, brigadão pela resposta hunternh!
Deu certinho aqui, abraços!
Primeiramente gostaria de lhe parabenizar pelo script, e por disponibilizar a comunidade. Minha dúvida é: existiria algumas forma de desabilitar as "scrollbars"? Tipo etsou utilizando a pop-up para exibir uma imagem, quando definida a altura e a largura ele não mostra a "scrollbars", porém ainda mostrar a o espaço da mesmas, gostaria que as mesmas redimensionasse de acordo com a imagem.
Caso, acho uma maneira agradeceria.
Grato,
Nando.
Primeiro pré-carregue todas as imagens dentro de um array
var img = new Array();
img[0] = new Image();
img[0].src="53_pics.jpg";
openPopup = function(titulo,num)
{
jQuery("#popup").html("<img src=\""+img[num].src+"\" alt=\"\" title=\"\" />");
var width = (jQuery.browser.msie)?(img[num].width+9):(img[num].width+9);
var height = (jQuery.browser.msie)?(img[num].height+29):(img[num].height+31);
var popup = new Popup("popup",width,height);
popup.setTitle(titulo);
popup.init();
popup.show();
};
para exibir, passe o titulo da imagem e o indice do array
<a href="#" onclick="openPopup('Nome da imagem',0);">Exibir popup</a>
Boa noite,
Gostei muito do seu codigo de popup e gostaria de tirar uma dúvida:
Eu já testei de várias formas, para abrir um popup com o seu código, clicando em uma outra página e ele colocar o conteúdo dentro do popup. A única maneira que eu consegui foi da sua maneira mesmo. Se não entendeu o que eu quis dizer, darei um exemplo:
Eu tenho uma página clientes.aspx e dentro dela, eu tenho um DataGrid onde em cima, eu tenho um link para cadastrar um novo cliente (cadcliente.aspx). Neste link, na hora que eu clicar, eu quero que vá para o popup o formulario de cadastro. Como é que eu faria? Pode me explicar?
Obrigado!
como faço pra abrir essa pop up junto com a pagina. Sem que o usuario tenha que clicar pra abrir ?
Apenas insira o código dentro da seção <head> do documento, sem atrelar à nenhuma função, ou à função window.onload
Tenta por um ID em cada popup para poder manipulá-los pelos seus ids para poder ter mais de um popup.
E põe para o icone se alterar quando clicar para minimizar, virar o ícone para maximizar e vice-versa.
muito legal..........
hunternh, da para colocar um griview no seu exemplo de pop up?
Nossa muito bom esse código! parabéns ao Wagner, pelo código e pela inciativa de disponibilizar tambem http://forum.imasters.com.br/public/style_emoticons/default/joia.gif
Eu testei e deu certinho aqui localmente mas quando eu subi pro meu site, o firebug apontou "jQuery is not defined" na funcção jQuery.create() do arquivo jquery-dom.
Alguem o que pode ser?
Valeu
Muito bom!Só achei uma coisa estranha. Se voce Minimizar e fechar, quando clicar no link denovo, aparece ele minimizado, ao invés de já aberto. Era para ser assim^? :Pabs