Javascript obtener una anchura actual Divs

  • Ginja_Ninja
  • Student
  • Student
  • No Avatar
  • Registrado: Dic 09, 2004
  • Mensajes: 89
  • Loc: UK
  • Status: Offline

Nota Febrero 17th, 2005, 3:47 am

Hola quiero hacer una función javascript que añade, 10, por ejemplo, a la actual anchura de un elemento Div.

No estoy seguro de cómo obtener la anchura actual.

Alguna idea?

TakeCare

G_N
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Febrero 17th, 2005, 3:47 am

  • katana
  • Mastermind
  • Mastermind
  • Avatar de Usuario
  • Registrado: Sep 07, 2004
  • Mensajes: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Nota Febrero 17th, 2005, 4:15 am

Dale a tu div una identificación para que pueda acceder a él fácilmente, y luego usar el "estilo" de propiedad para obtener el ancho:
Código: [ Select ]
var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.style.width;
// now add 10 to the width
mydiv.style.width = curr_width + 10;
  1. var mydiv = document.getElementById("mydiv");
  2. var curr_width = mydiv.style.width;
  3. // now add 10 to the width
  4. mydiv.style.width = curr_width + 10;
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • katana
  • Mastermind
  • Mastermind
  • Avatar de Usuario
  • Registrado: Sep 07, 2004
  • Mensajes: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Nota Febrero 17th, 2005, 4:40 am

Si has probado el ejemplo anterior, usted puede estar experimentando problemas con el código. Es posible que funcione en IE, Firefox, pero no le gusta. Ajuste de la anchura inicial DIVs usando CSS no funciona por alguna razón - Firefox devuelve un valor nulo para style.width el atributo "". Para evitar este problema, establezca la anchura inicial de la DIV en el "estilo" atributo de la etiqueta DIV. Esto se asegurará de que Firefox se obtiene un valor para la anchura inicial.
Heres el código que utiliza para probar que:
Código: [ Select ]
<html>
<head>
<style type="text/css">
div#mydiv {
    width: 100px;
    height: 100px;
    background-color: red;
}
</style>
<script language="JavaScript">
function addWidth() {
    var mydiv = document.getElementById("mydiv");
    var curr_width = parseInt(mydiv.style.width); // removes the "px" at the end
    mydiv.style.width = (curr_width + 10) +"px";
}
</script>
</head>
<body>
<input type="button" value="Make Bigger" onclick="addWidth()" />
<div id="mydiv" style="width:100px"></div>
</body>
</html>
  1. <html>
  2. <head>
  3. <style type="text/css">
  4. div#mydiv {
  5.     width: 100px;
  6.     height: 100px;
  7.     background-color: red;
  8. }
  9. </style>
  10. <script language="JavaScript">
  11. function addWidth() {
  12.     var mydiv = document.getElementById("mydiv");
  13.     var curr_width = parseInt(mydiv.style.width); // removes the "px" at the end
  14.     mydiv.style.width = (curr_width + 10) +"px";
  15. }
  16. </script>
  17. </head>
  18. <body>
  19. <input type="button" value="Make Bigger" onclick="addWidth()" />
  20. <div id="mydiv" style="width:100px"></div>
  21. </body>
  22. </html>
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • Ginja_Ninja
  • Student
  • Student
  • No Avatar
  • Registrado: Dic 09, 2004
  • Mensajes: 89
  • Loc: UK
  • Status: Offline

Nota Febrero 17th, 2005, 5:15 am

una palabra - PERFECTA -

Muchas gracias thatsreally buena

Ten cuidado

G_N
  • RichB
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: May 17, 2003
  • Mensajes: 1121
  • Loc: Boston
  • Status: Offline

Nota Febrero 17th, 2005, 5:16 am

Sí, usted no puede recuperar el estilo de valores utilizando ob.style.width menos theyve ha establecido mediante un estilo en línea. Hay una forma de evitar esto que me encontré el año pasado mientras trabajaba en un problema con alguien aquí en Ozzu. Se recupera el valor si se ha establecido en línea o en un integrado o externo (creo) de hojas de estilo, pero el valor debe ser ajustado a través de CSS antes de la función se llama porque IE devolverá un valor de cadena "auto" en lugar de el valor calculado de la anchura real de que Mozilla devolverá si no se establece el valor en algún lugar.

Código: [ Select ]
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
<!--
function getStyle(el, style) {
  if(!document.getElementById) return;
 
   var value = el.style[toCamelCase(style)];
 
  if(!value)
    if(document.defaultView)
      value = document.defaultView.
         getComputedStyle(el, "").getPropertyValue(style);
   
    else if(el.currentStyle)
      value = el.currentStyle[toCamelCase(style)];
  
   return value;
}

function setStyle(objId, style, value) {
  document.getElementById(objId).style[style] = value;
}

function toCamelCase( sInput ) {
  var oStringList = sInput.split('-');
  if(oStringList.length == 1)  
    return oStringList[0];
  var ret = sInput.indexOf("-") == 0 ?
      oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
  for(var i = 1, len = oStringList.length; i < len; i++){
    var s = oStringList[i];
    ret += s.charAt(0).toUpperCase() + s.substring(1)
  }
  return ret;
}

function increaseWidth(addToWidth, whichDiv){
  var theDiv = document.getElementById(whichDiv);
  var currWidth = parseInt(getStyle(theDiv, "width"));
  var newWidth = currWidth + parseInt(addToWidth);
  setStyle(whichDiv, "width", newWidth + "px");
}
// -->
</script>
<style type="text/css">
<!--
.testDiv {width: 200px; background-color:#ccc }
-->
</style>
</head>
<body>
<div id="test" style="width:200px; background-color:#ccc">Yada</div>
<div id="test2" class="testDiv">Yada</div>

<form name="testForm" action="">
<label> Add: <input name="newWidth" value="10" type="text" /></label><br>
<label> Add: <input name="testDiv" value="test" type="text" /></label><br>
<input type="button" value="Add to Width" onclick="increaseWidth(document.testForm.newWidth.value, document.testForm.testDiv.value)" />
</form>
</body>
</html>
  1. <html>
  2. <head>
  3. <title>Untitled</title>
  4. <script type="text/javascript">
  5. <!--
  6. function getStyle(el, style) {
  7.   if(!document.getElementById) return;
  8.  
  9.    var value = el.style[toCamelCase(style)];
  10.  
  11.   if(!value)
  12.     if(document.defaultView)
  13.       value = document.defaultView.
  14.          getComputedStyle(el, "").getPropertyValue(style);
  15.    
  16.     else if(el.currentStyle)
  17.       value = el.currentStyle[toCamelCase(style)];
  18.   
  19.    return value;
  20. }
  21. function setStyle(objId, style, value) {
  22.   document.getElementById(objId).style[style] = value;
  23. }
  24. function toCamelCase( sInput ) {
  25.   var oStringList = sInput.split('-');
  26.   if(oStringList.length == 1)  
  27.     return oStringList[0];
  28.   var ret = sInput.indexOf("-") == 0 ?
  29.       oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
  30.   for(var i = 1, len = oStringList.length; i < len; i++){
  31.     var s = oStringList[i];
  32.     ret += s.charAt(0).toUpperCase() + s.substring(1)
  33.   }
  34.   return ret;
  35. }
  36. function increaseWidth(addToWidth, whichDiv){
  37.   var theDiv = document.getElementById(whichDiv);
  38.   var currWidth = parseInt(getStyle(theDiv, "width"));
  39.   var newWidth = currWidth + parseInt(addToWidth);
  40.   setStyle(whichDiv, "width", newWidth + "px");
  41. }
  42. // -->
  43. </script>
  44. <style type="text/css">
  45. <!--
  46. .testDiv {width: 200px; background-color:#ccc }
  47. -->
  48. </style>
  49. </head>
  50. <body>
  51. <div id="test" style="width:200px; background-color:#ccc">Yada</div>
  52. <div id="test2" class="testDiv">Yada</div>
  53. <form name="testForm" action="">
  54. <label> Add: <input name="newWidth" value="10" type="text" /></label><br>
  55. <label> Add: <input name="testDiv" value="test" type="text" /></label><br>
  56. <input type="button" value="Add to Width" onclick="increaseWidth(document.testForm.newWidth.value, document.testForm.testDiv.value)" />
  57. </form>
  58. </body>
  59. </html>


Puede probar cambiando la div de "prueba" a "test2" - el primero utiliza un estilo en línea y la segunda de una clase en una hoja de estilos incrustada. Sin embargo, si se quita el valor de ancho en el CSS para el IE div informará de un error y detener la secuencia de comandos. No creo que los theres de todas formas en torno a este, porque no creo que se pueda recuperar el valor calculado a partir de auto del IE, pero debería funcionar siempre y cuando el div tiene un valor inicial de CSS para la anchura, con independencia de la CSS en línea, incrustado o externo.

El código de las funciones que obtener y definir los estilos de vino de aquí:

http://dhtmlkitchen.com/learn/js/setstyle/index4.jsp
http://dhtmlkitchen.com/learn/js/setstyle/index3.jsp
Free Programming Resources
  • katana
  • Mastermind
  • Mastermind
  • Avatar de Usuario
  • Registrado: Sep 07, 2004
  • Mensajes: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Nota Febrero 17th, 2005, 5:19 am

Cosas interesantes. Yo inicialmente tenía mi bloque de secuencia de comandos antes de mi bloque de CSS, así que me cambié en torno a las dos para ver si tendría que hacer ninguna diferencia, pero no.
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • RichB
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: May 17, 2003
  • Mensajes: 1121
  • Loc: Boston
  • Status: Offline

Nota Febrero 17th, 2005, 5:23 am

Sí, esas funciones han llegado a mano una o dos veces, pero que necesitan cuidado de los ensayos con los distintos valores, debido a las diversas peculiaridades del navegador. Por ejemplo, es decir, con colores como el retorno hexadecimal trillizos o valores literales como "azul" - básicamente cualquier cosa que ceder, pero mozilla regresa como RBG (100, 100, 100) cadena de estilo, independientemente de cómo establecer la propiedad inicialmente.
Free Programming Resources
  • katana
  • Mastermind
  • Mastermind
  • Avatar de Usuario
  • Registrado: Sep 07, 2004
  • Mensajes: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Nota Febrero 17th, 2005, 5:59 am

Un día, IE y Firefox trabajarán juntos en perfecta armonía. Para ver una indicación de ese día, haga clic en aquí
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • RichB
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: May 17, 2003
  • Mensajes: 1121
  • Loc: Boston
  • Status: Offline

Nota Febrero 17th, 2005, 6:11 am

heheh, yo necesitaba una risa. gracias :)
Free Programming Resources
  • dimat
  • Student
  • Student
  • Avatar de Usuario
  • Registrado: Ago 02, 2006
  • Mensajes: 67
  • Loc: Kiev, Ukraine
  • Status: Offline

Nota Enero 28th, 2008, 3:40 am

He encontrado otra solución:
div ha offsetWidth propiedad:
Código: [ Select ]
document.getElementsByTagName("div")["someDiv"].offsetWidth

bruja representa su ancho real. pero! que es real sólo después de todo el contenido esté cargado en el div. Por ejemplo, si contiene la imagen:
Código: [ Select ]
<div id="someDiv"><img src="1024x768.png" /></div>

usted puede obtener 40 de ancho, porque hasta que la imagen no se ha descargado es reemplazado con el símbolo de la anchura de la imagen de brujas es de 40. así que si desea calcutate todos widthes de las imágenes en la página web, youd mejor hacerlo en el evento onLoad.
Código: [ Select ]
<body onLoad="CalculateAllImageWidthes()">
....
</body>
  1. <body onLoad="CalculateAllImageWidthes()">
  2. ....
  3. </body>

PS offsetWidth se define no sólo para los elementos div y trabaja para todo tipo de navegadores.
  • katana
  • Mastermind
  • Mastermind
  • Avatar de Usuario
  • Registrado: Sep 07, 2004
  • Mensajes: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Nota Enero 28th, 2008, 6:32 am

Haha, si sólo yo sabía entonces lo que sé ahora! Cuando leí el título de este post, he pensado a mí mismo - "Fácil, el uso" offsetWidth "", entonces yo vi que había respondido efectivamente a él en primer lugar!

Sí, si yo estaba respondiendo ahora, recomendamos que utilices Id offsetWidth. El uso de "style.width" sólo funciona si establece el ancho a través de CSS en el primer lugar, que no es una solución ideal, especialmente si establece el ancho utilizando porcentajes, etc
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • dimat
  • Student
  • Student
  • Avatar de Usuario
  • Registrado: Ago 02, 2006
  • Mensajes: 67
  • Loc: Kiev, Ukraine
  • Status: Offline

Nota Enero 28th, 2008, 7:22 am

este vínculos neerly va primero cuando google "javascript div ancho", así que decidí que sería bueno si visiters se encuentre la respuesta aquí
  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Registrado: Feb 10, 2004
  • Mensajes: 13455
  • Loc: Florida
  • Status: Offline

Nota Enero 28th, 2008, 3:09 pm

Originalmente pensé identificador de bloqueo de otro hilo de edad siendo golpeado por el spam.

Este es un buen ejemplo de cuando golpear hilos de edad no es una idea tan mala.

Im curioso de este embargo,
Código: [ Select ]
document.getElementsByTagName("div")["someDiv"].offsetWidth


Puedes tener acceso a elementos específicos de identificación de getElementsByTagName así?
Pensé que sólo el índice numérico se dispone de cross-browser.
Código: [ Select ]
document.getElementsByTagName("div")[0].offsetWidth
Strong with this one, the sudo is.
  • katana
  • Mastermind
  • Mastermind
  • Avatar de Usuario
  • Registrado: Sep 07, 2004
  • Mensajes: 2390
  • Loc: Edinburgh, Scotland
  • Status: Offline

Nota Enero 29th, 2008, 2:46 am

Hmm, ¿no cree que la sintaxis funcionaría bien, sin embargo a pensar en ello, yo no veía ningún motivo que wouldnt. Yo nunca había usado antes. Acabo probado en Firefox, IE6 y Opera y parece funcionar bien. Supongo que esa es un poco más robusto que simplemente especificando el índice del elemento que desea cambiar (índice es más probable que el cambio que el elemento de identificación).

Aprender algo nuevo cada día.
Why do geeks get Halloween and Christmas confused?
Because 31 Oct == 25 Dec
www.darren-king.co.uk
  • josepharistotil
  • Born
  • Born
  • No Avatar
  • Registrado: Sep 13, 2008
  • Mensajes: 1
  • Status: Offline

Nota Septiembre 13th, 2008, 1:06 am

¿Es usted intenta esto como lo siguiente?
para encontrar ancho
Código: [ Select ]
document.getElementById("<DivName>").offsetWidth;

de fiding altura
Código: [ Select ]
document.getElementById("<DivName>").offsetHeight;
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Septiembre 13th, 2008, 1:06 am

Publicar Información

  • Total de mensajes en este tema: 18 mensajes
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 176 invitados
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC