Javascript obtener una anchura actual Divs

  • mlarson154
  • Novice
  • Novice
  • Avatar de Usuario
  • Registrado: Jun 23, 2005
  • Mensajes: 15
  • Loc: Utah, USA
  • Status: Offline

Nota Octubre 7th, 2009, 1:08 pm

Sé que esto es una entrada antigua, pero he visto un montón de posts en los foros de muchos cambios en relación con el ancho de vía. Style.width sin ninguna respuesta clara de por qué no funciona. Lo que encontré es que el <div> debe cargar antes de poder cambiar, así que llamando a su función en la cabecera no devuelve nada ya que el <div> sí no se ha cargado.

Por lo tanto, llame a su función después de la <div>:
Código: [ Select ]
<head>
<script type="text/javascript"> function WidthChange()
{
document.getElementById("DivName").style.width = '100px';
}
</script>
</head>
<body>
<div id="DivName">
<script type="text/javascript">WidthChange()</script>
...
  1. <head>
  2. <script type="text/javascript"> function WidthChange()
  3. {
  4. document.getElementById("DivName").style.width = '100px';
  5. }
  6. </script>
  7. </head>
  8. <body>
  9. <div id="DivName">
  10. <script type="text/javascript">WidthChange()</script>
  11. ...


Usted puede especificar la función llamada en cualquier momento después de la línea de div, así que usted puede ponerlo abajo junto a la etiqueta </ body>, si quieres.

Así es como me di cuenta de que podía utilizar. Style.width. ¿Alguien tiene una corrección a esto? No he podido encontrar NINGUNA manera de hacer la función de llamada antes de la línea de div.
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Octubre 7th, 2009, 1:08 pm

  • creatino
  • Born
  • Born
  • No Avatar
  • Registrado: Oct 29, 2009
  • Mensajes: 1
  • Status: Offline

Nota Octubre 29th, 2009, 12:22 pm

Hola chicos,

Gracias por ambos métodos, tanto sentido y los resultados fueron sólo es útil después de googlear mucho. Soy bastante nuevo en JS y CSS, pero una buena actionscripter.

Im pruebas de ambos métodos y parecen estar recibiendo valores diferentes a ellos. Además de eso, Firefox 3.5.4 no quiere que me muestre las dos alertas siguientes Im usando durante la prueba: Safari lo hace bien. Cualquier idea por qué puede ser? Necesito ese valor como base para una animación js.

HTML Código: [ Select ]
<script type="text/javascript">
   alert(getStyle(item3, "width"));
   alert(document.getElementById("item1").offsetWidth);
</script>
  1. <script type="text/javascript">
  2.    alert(getStyle(item3, "width"));
  3.    alert(document.getElementById("item1").offsetWidth);
  4. </script>


Ayuda apreciado, thnx!
Moderator Remark: Added [code] tags
  • dbind
  • Born
  • Born
  • No Avatar
  • Registrado: Oct 22, 2010
  • Mensajes: 1
  • Status: Offline

Nota Octubre 22nd, 2010, 9:35 am

@ RichB: su toCamelCase () función podría ser mejorado y simplificado mediante el uso de expresiones regulares:

toCamelCase función (sInput) {
sInput.replace retorno (/-([ a-zA-Z]) / función g, (s, s1) {
s1.toUpperCase retorno ();
});
};

Espero que ayude a alguien.

[Quote = "RichB"] Sí, no se puede recuperar el estilo de valores mediante ob.style.width menos theyve definido con 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 más aquí en Ozzu. Se recuperará el valor si se ha establecido en línea o en una hoja de estilos incrustada o externo (creo), pero el valor debe ser ajustado a través de CSS antes de la función se llama porque el IE devolverá un valor de cadena "auto" en lugar de el valor calculado de la anchura real de que Mozilla va a volver si no se establece el valor en alguna parte.

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 el div de "prueba" a "test2" - la primera utiliza un estilo en línea y una clase el segundo en una hoja de estilos incrustada. Sin embargo, si se quita el valor de la anchura de la CSS, ya sea para div IE informar de un error y detener la secuencia de comandos. No creo que los theres de todas formas todo esto porque yo no creo que se puede recuperar el valor de automóviles calculado a partir de IE, pero debería funcionar siempre y cuando el div tiene un valor inicial de CSS para el ancho, con independencia de la CSS en línea, integrados o externos.

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

[...]
[...]

Publicar Información

  • Total de mensajes en este tema: 18 mensajes
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 220 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