From 4f0e1ec1c2772904c033f747dc38a08223e8d661 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 13:42:10 -0400 Subject: delete pages that were never translated from en-US (es, part 2) (#1550) --- files/es/web/api/audionode/index.html | 154 ---- .../hit_regions_and_accessibility/index.html | 100 --- files/es/web/api/filesystem/index.html | 118 --- files/es/web/api/headers/index.html | 135 --- .../recommended_drag_types/index.html | 145 ---- .../es/web/api/htmlcanvaselement/toblob/index.html | 261 ------ files/es/web/api/mediasource/index.html | 182 ----- files/es/web/api/webvtt_api/index.html | 903 --------------------- .../api/window/domcontentloaded_event/index.html | 149 ---- files/es/web/api/worker/postmessage/index.html | 206 ----- .../index.html | 232 ------ files/es/web/css/@document/index.html | 82 -- files/es/web/css/background-position-x/index.html | 126 --- files/es/web/css/border-radius/index.html | 320 -------- files/es/web/css/cascade/index.html | 202 ----- files/es/web/css/clip-path/index.html | 179 ---- .../media_queries/testing_media_queries/index.html | 94 --- .../es/web/html/attributes/autocomplete/index.html | 181 ----- files/es/web/html/element/shadow/index.html | 153 ---- .../global_objects/encodeuricomponent/index.html | 162 ---- .../reference/statements/with/index.html | 167 ---- files/es/web/mathml/authoring/index.html | 415 ---------- files/es/web/mathml/authoring/openoffice.png | Bin 12489 -> 0 bytes files/es/web/media/formats/index.html | 88 -- files/es/web/svg/element/foreignobject/index.html | 133 --- files/es/web/xslt/element/number/index.html | 170 ---- 26 files changed, 5057 deletions(-) delete mode 100644 files/es/web/api/audionode/index.html delete mode 100644 files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html delete mode 100644 files/es/web/api/filesystem/index.html delete mode 100644 files/es/web/api/headers/index.html delete mode 100644 files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html delete mode 100644 files/es/web/api/htmlcanvaselement/toblob/index.html delete mode 100644 files/es/web/api/mediasource/index.html delete mode 100644 files/es/web/api/webvtt_api/index.html delete mode 100644 files/es/web/api/window/domcontentloaded_event/index.html delete mode 100644 files/es/web/api/worker/postmessage/index.html delete mode 100644 files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html delete mode 100644 files/es/web/css/@document/index.html delete mode 100644 files/es/web/css/background-position-x/index.html delete mode 100644 files/es/web/css/border-radius/index.html delete mode 100644 files/es/web/css/cascade/index.html delete mode 100644 files/es/web/css/clip-path/index.html delete mode 100644 files/es/web/css/media_queries/testing_media_queries/index.html delete mode 100644 files/es/web/html/attributes/autocomplete/index.html delete mode 100644 files/es/web/html/element/shadow/index.html delete mode 100644 files/es/web/javascript/reference/global_objects/encodeuricomponent/index.html delete mode 100644 files/es/web/javascript/reference/statements/with/index.html delete mode 100644 files/es/web/mathml/authoring/index.html delete mode 100644 files/es/web/mathml/authoring/openoffice.png delete mode 100644 files/es/web/media/formats/index.html delete mode 100644 files/es/web/svg/element/foreignobject/index.html delete mode 100644 files/es/web/xslt/element/number/index.html (limited to 'files/es/web') diff --git a/files/es/web/api/audionode/index.html b/files/es/web/api/audionode/index.html deleted file mode 100644 index ea6ff34406..0000000000 --- a/files/es/web/api/audionode/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: AudioNode -slug: Web/API/AudioNode -translation_of: Web/API/AudioNode ---- -
{{APIRef("Web Audio API")}}
- -

La interfaz AudioNode es una interfaz genérica para representar un módulo de procesamiento de audio. Ejemplos:

- - - -

{{InheritanceDiagram}}

- -

Note: An AudioNode can be target of events, por lo tanto este implementa  {{domxref("EventTarget")}} interface.

- -

Descripción

- -

The audio routing graph

- -

AudioNodes participating in an AudioContext create a audio routing graph.

- -

Cada AudioNode posee entradas y salidas, y múltiples nodos de audio son conectados para construir un processing graph. Este graph es contenido en {{domxref("AudioContext")}}, y cada nodo de audio solo puede pertecener a un audio context.

- -

Un source node tiene cero entradas pero una o muchas salidas, y puede ser usado para generar sonido. Por otro lado, un destination node no tiene salidas; instead, all its inputs are directly played back on the speakers (or whatever audio output device the audio context uses). In addition, there are processing nodes which have inputs and outputs. The exact processing done varies from one AudioNode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the {{domxref("AnalyserNode")}}, where the result of the processing is accessed separately).

- -

The more nodes in a graph, the higher the latency will be. Por ejemplo, si tu graph tiene una latencia de 500ms, Cuando el source node reproduzca un sonido, este va a tomar la mitad de un segundo hasta que el sonido pueda ser escuchado en tus altavoces. (or even longer because of latency in the underlying audio device). Por lo tanto, si tu necesitas tener un audio interactivo, keep the graph as small as possible, and put user-controlled audio nodes at the end of a graph. For example, a volume control (GainNode) should be the last node so that volume changes take immediate effect.

- -

Each input and output has a given amount of channels. For example, mono audio has one channel, while stereo audio has two channels. The Web Audio API will up-mix or down-mix the number of channels as required; check the Web Audio spec for details.

- -

For a list of all audio nodes, see the Web Audio API homepage.

- -

Creating an AudioNode

- -

There are two ways to create an AudioNode: via the constuctor and via the factory method.

- -
// constructor
-const analyserNode = new AnalyserNode(audioCtx, {
-  fftSize: 2048,
-  maxDecibels: -25,
-  minDecibels: -60,
-  smoothingTimeConstant: 0.5,
-});
-
-// factory method
-const analyserNode = audioCtx.createAnalyser();
-analyserNode.fftSize = 2048;
-analyserNode.maxDecibels = -25;
-analyserNode.minDecibels = -60;
-analyserNode.smoothingTimeConstant = 0.5;
- -

Eres libre de usar cualquiera de los constructors o factory methods, o una mezcla de ambos, sin embargo hay ventajas al usar contructores:

- - - -

Tener en cuenta que Microsoft Edge does not yet appear to support the constructors; it will throw a "Function expected" error when you use the constructors.

- -

Brief history: The first version of the Web Audio spec only defined the factory methods. After a design review in October 2013, it was decided to add constructors because they have numerous benefits over factory methods. The constructors were added to the spec from August to October 2016. Factory methods continue to be included in the spec and are not deprecated.

- -

Properties

- -
-
{{domxref("AudioNode.context")}} {{readonlyInline}}
-
Returns the associated {{domxref("BaseAudioContext")}}, that is the object representing the processing graph the node is participating in.
-
- -
-
{{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}
-
Returns the number of inputs feeding the node. Source nodes are defined as nodes having a numberOfInputs property with a value of 0.
-
- -
-
{{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}
-
Returns the number of outputs coming out of the node. Destination nodes — like {{ domxref("AudioDestinationNode") }} — have a value of 0 for this attribute.
-
- -
-
{{domxref("AudioNode.channelCount")}}
-
Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. Its usage and precise definition depend on the value of {{domxref("AudioNode.channelCountMode")}}.
-
- -
-
{{domxref("AudioNode.channelCountMode")}}
-
Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.
-
{{domxref("AudioNode.channelInterpretation")}}
-
Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio up-mixing and down-mixing will happen.
- The possible values are "speakers" or "discrete".
-
- -

Methods

- -

Also implements methods from the interface {{domxref("EventTarget")}}.

- -
-
{{domxref("AudioNode.connect()")}}
-
Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an {{domxref("AudioParam")}}.
-
{{domxref("AudioNode.disconnect()")}}
-
Allows us to disconnect the current node from another one it is already connected to.
-
- -

Example

- -

This simple snippet of code shows the creation of some audio nodes, and how the AudioNode properties and methods can be used. You can find examples of such usage on any of the examples linked to on the Web Audio API landing page (for example Violent Theremin.)

- -
const audioCtx = new AudioContext();
-
-const oscillator = new OscillatorNode(audioCtx);
-const gainNode = new GainNode(audioCtx);
-
-oscillator.connect(gainNode).connect(audioCtx.destination);
-
-oscillator.context;
-oscillator.numberOfInputs;
-oscillator.numberOfOutputs;
-oscillator.channelCount;
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-audionode-interface', 'AudioNode')}}{{Spec2('Web Audio API')}} 
- -

Browser compatibility

- -
- - -

{{Compat("api.AudioNode")}}

-
- -

See also

- - diff --git a/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html b/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html deleted file mode 100644 index 1f2a93dbae..0000000000 --- a/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Hit regions and accessibility -slug: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility -translation_of: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility -original_slug: Web/Guide/HTML/Canvas_tutorial/Hit_regions_and_accessibility ---- -
{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
- -
The {{HTMLElement("canvas")}} element on its own is just a bitmap and does not provide information about any drawn objects. Canvas content is not exposed to accessibility tools like semantic HTML is. In general, you should avoid using canvas in an accessible website or app. The following guidelines can help to make it more accessible.
- -
El elemento {{HTMLElement ("canvas")}} por sí solo es solo un mapa de bits y no proporciona información sobre ningún objeto dibujado. El contenido del lienzo no está expuesto a herramientas de accesibilidad como el HTML semántico. En general, debe evitar usar canvas en un sitio web o aplicación accesible. Las siguientes pautas pueden ayudar a que sea más accesible.
- -

Fallback content

- -

The content inside the <canvas> ... </canvas> tags can be used as a fallback for browsers which don't support canvas rendering. It's also very useful for assistive technology users (like screen readers) which can read and interpret the sub DOM in it. A good example at html5accessibility.com demonstrates how this can be done:

- -
<canvas>
-  <h2>Shapes</h2>
-  <p>A rectangle with a black border.
-   In the background is a pink circle.
-   Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>.
-   Partially overlaying the circle is a green
-   <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a>
-   and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>,
-   both of which are semi-opaque, so the full circle can be seen underneath.</p>
-</canvas> 
- -

See the video how NVDA reads this example by Steve Faulkner.

- -

ARIA rules

- -

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications more accessible to people with disabilities. You can use ARIA attributes to describe the behavior and purpose of the canvas element. See ARIA and ARIA techniques for more information.

- -
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas>
-
- -

Hit regions

- -

Whether the mouse coordinates are within a particular area on the canvas, is a common problem to solve. The hit region API allows you to define an area of your canvas and provides another possibility to expose interactive content on a canvas to accessibility tools. It allows you to make hit detection easier and lets you route events to DOM elements. The API has the following three methods (which are still experimental in current web browsers; check the browser compatibility tables).

- -
-
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
-
Adds a hit region to the canvas.
-
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
-
Removes the hit region with the specified id from the canvas.
-
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
-
Removes all hit regions from the canvas.
-
- -

You can add a hit region to your path and check for the {{domxref("MouseEvent.region")}} property to test if your mouse is hitting your region, for example.

- -
<canvas id="canvas"></canvas>
-<script>
-var canvas = document.getElementById('canvas');
-var ctx = canvas.getContext('2d');
-
-ctx.beginPath();
-ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
-ctx.fill();
-ctx.addHitRegion({id: 'circle'});
-
-canvas.addEventListener('mousemove', function(event) {
-  if (event.region) {
-    alert('hit region: ' + event.region);
-  }
-});
-</script>
- -

The addHitRegion() method also takes a control option to route events to an element (that is a descendant of the canvas):

- -
ctx.addHitRegion({control: element});
- -

This can be useful for routing to {{HTMLElement("input")}} elements, for example. See also this codepen demo.

- -

Focus rings

- -

When working with the keyboard, focus rings are a handy indicator to help navigating on a page. To draw focus rings on a canvas drawing, the drawFocusIfNeeded property can be used.

- -
-
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}
-
If a given element is focused, this method draws a focus ring around the current path.
-
- -

Additionally, the scrollPathIntoView() method can be used to make an element visible on the screen if focused, for example.

- -
-
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}
-
Scrolls the current path or a given path into the view.
-
- -

See also

- - - -
{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
diff --git a/files/es/web/api/filesystem/index.html b/files/es/web/api/filesystem/index.html deleted file mode 100644 index 62f5e91b4b..0000000000 --- a/files/es/web/api/filesystem/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: FileSystem -slug: Web/API/FileSystem -translation_of: Web/API/FileSystem ---- -

{{APIRef("File System API")}} {{non-standard_header}}

- -

La interfaz de la API FileSystem  para la entrada de archivos y directorios es usada para representar un sistema de archivos.  Estos objetos pueden ser obtenidos desde la propiedad {{domxref("FileSystemEntry.filesystem", "filesystem")}} en cualquier entrada del sistema de archivos . Algunos navegadores ofrecen APIs adicionales para crear y administrar el sistema de archivos , como el metodo de Chrome {{domxref("Window.requestFileSystem", "requestFileSystem()")}}.

- -

This interface will not grant you access to the users filesystem. Instead you will have a "virtual drive" within the browser sandbox. If you want to gain access to the users filesystem you need to invoke the user by eg. installing a Chrome extension. The relevant Chrome API can be found here.

- -
-

Because this is a non-standard API, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. Check the {{anch("Browser compatibility")}} section for details.

-
- -

Conceptos Basicos

- -

Hay dos formas de acceder a un objeto FileSystem :

- -
    -
  1. You can directly ask for one representing a sandboxed file system created just for your web app directly by calling window.requestFileSystem().  If that call is successful, it executes a callback handler, which receives as a parameter a FileSystem object describing the file system.
  2. -
  3. You can get it from a file system entry object, through its {{domxref("FileSystemEntry.filesystem", "filesystem")}} property.
  4. -
- -

Propiedades

- -
-
{{domxref("FileSystem.name")}} {{ReadOnlyInline}}
-
A {{domxref("USVString")}} representing the file system's name. This name is unique among the entire list of exposed file systems.
-
{{domxref("FileSystem.root")}} {{ReadOnlyInline}}
-
A {{domxref("FileSystemDirectoryEntry")}} object which represents the file system's root directory. Through this object, you can gain access to all files and directories in the file system.
-
- -

Especificaciones

- - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
- -

This API has no official W3C or WHATWG specification.

- -

Compatibilidad entre navegadores 

- -

{{ CompatibilityTable }}

- -
- - - - - - - - - - - - - - - - - - - - - -
CaracteristicaChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Soporte basico13{{ property_prefix("webkit") }}{{ CompatGeckoDesktop(50) }}{{ CompatNo }}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}} {{ property_prefix("webkit") }}{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo }}0.16{{ property_prefix("webkit") }}{{ CompatGeckoMobile(50) }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[1] Microsoft Edge implements this interface under the name WebKitFileSystem, and supports its use only in drag-and-drop scenarios using the {{domxref("DataTransferItem.webkitGetAsEntry()")}} method. It's not available for use in file or folder picker panels (such as when you use an {{HTMLElement("input")}} element with the {{domxref("HTMLInputElement.webkitdirectory")}} attribute.

- -

See also

- - diff --git a/files/es/web/api/headers/index.html b/files/es/web/api/headers/index.html deleted file mode 100644 index cb65b6aa11..0000000000 --- a/files/es/web/api/headers/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Headers -slug: Web/API/Headers -tags: - - API - - Experimental - - Fetch - - Headers - - Interface - - Reference -translation_of: Web/API/Headers ---- -
{{ APIRef("Fetch") }}
- -
La interfaz Headers de la Fetch API permite realizar diversas acciones en los Headers de solicitud y respuesta HTTP.Estas acciones incluyen recuperar, establecer, agregar y eliminar. Un objeto Header tiene una lista  asociada que inicialmente está vacía, y consta de cero o más pares de nombre y valor.
- -
Es posible añadir metodos de uso como {{domxref("Headers.append","append()")}} (ver{{anch(" ejemplos")}}.) En todos los métodos de esta interfaz, los nombres de los encabezados se relacionan con una secuencia de bytes sensible a mayúsculas y minúsculas.
- -
Por razones de seguridad, algunos headers pueden ser controlados unicamente por el user agent. Estos headers incluyen los {{Glossary("Forbidden_header_name", "nombres prohibidos para headers", 1)}}  y {{Glossary("Forbidden_response_header_name", "nombres prohibidos de Headers response", 1)}}.
- -

A Headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none. This affects whether the {{domxref("Headers.set","set()")}}, {{domxref("Headers.delete","delete()")}}, and {{domxref("Headers.append","append()")}} methods will mutate the header. For more information see {{Glossary("Guard")}}.

- -

You can retrieve a Headers object via the {{domxref("Request.headers")}} and {{domxref("Response.headers")}} properties, and create a new Headers object using the {{domxref("Headers.Headers()")}} constructor.

- -

An object implementing Headers can directly be used in a {{jsxref("Statements/for...of", "for...of")}} structure, instead of {{domxref('Headers.entries()', 'entries()')}}: for (var p of myHeaders) is equivalent to for (var p of myHeaders.entries()).

- -
-

Note: you can find more out about the available headers by reading our HTTP headers reference.

-
- -

Constructor

- -
-
{{domxref("Headers.Headers()")}}
-
Creates a new Headers object.
-
- -

Methods

- -
-
{{domxref("Headers.append()")}}
-
Appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.
-
{{domxref("Headers.delete()")}}
-
Deletes a header from a Headers object.
-
{{domxref("Headers.entries()")}}
-
Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.
-
{{domxref("Headers.forEach()")}}
-
Executes a provided function once for each array element.
-
{{domxref("Headers.get()")}}
-
Returns a {{domxref("ByteString")}} sequence of all the values of a header within a Headers object with a given name.
-
{{domxref("Headers.has()")}}
-
Returns a boolean stating whether a Headers object contains a certain header.
-
{{domxref("Headers.keys()")}}
-
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all keys of the key/value pairs contained in this object.
-
{{domxref("Headers.set()")}}
-
Sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
-
{{domxref("Headers.values()")}}
-
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all values of the key/value pairs contained in this object.
-
- -
-

Note: To be clear, the difference between {{domxref("Headers.set()")}} and {{domxref("Headers.append()")}} is that if the specified header does already exist and does accept multiple values, {{domxref("Headers.set()")}} will overwrite the existing value with the new one, whereas {{domxref("Headers.append()")}} will append the new value onto the end of the set of values. See their dedicated pages for example code.

-
- -
-

Note: All of the Headers methods will throw a TypeError if you try to pass in a reference to a name that isn't a valid HTTP Header name. The mutation operations will throw a TypeError if the header has an immutable {{Glossary("Guard")}}. In any other failure case they fail silently.

-
- -
-

Note: When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.

-
- -

Obsolete methods

- -
-
{{domxref("Headers.getAll()")}}
-
Used to return an array of all the values of a header within a Headers object with a given name; this method has now been deleted from the spec, and {{domxref("Headers.get()")}} now returns all values instead of just one.
-
- -

Examples

- -

In the following snippet, we create a new header using the Headers() constructor, add a new header to it using append(), then return that header value using get():

- -
var myHeaders = new Headers();
-
-myHeaders.append('Content-Type', 'text/xml');
-myHeaders.get('Content-Type') // should return 'text/xml'
-
- -

The same can be achieved by passing an array of arrays or an object literal to the constructor:

- -
var myHeaders = new Headers({
-    'Content-Type': 'text/xml'
-});
-
-// or, using an array of arrays:
-myHeaders = new Headers([
-    ['Content-Type', 'text/xml']
-]);
-
-myHeaders.get('Content-Type') // should return 'text/xml'
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#headers-class','Headers')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

{{Compat("api.Headers")}}

- -

See also

- - - -

 

diff --git a/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html b/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html deleted file mode 100644 index 84b04854fa..0000000000 --- a/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Tipos de Drag recomendados -slug: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types -translation_of: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types -original_slug: DragDrop/Recommended_Drag_Types ---- -

A continuación se describe la mejor practica para utilizar los datos a ser arrastrado.

-

Arrastramdo Texto

-

Al arrastrar el texto, utilice el texto / texto normal. Los datos deben ser la cadena de arrastre. Por ejemplo:

-
event.dataTransfer.setData("text/plain", "This is text to drag")
-
-

Arrastrar texto en cuadros de texto y las selecciones de las páginas web se realiza de forma automática, por lo que no es necesario para manejar dragging.

-

Se recomienda que siempre se agrega datos del tipo  text/plain  como un mensaje para las aplicaciones o los destinos que no soportan otros tipos, a menos que no hay alternativa de texto lógico. Siempre agregue el tipo de texto sin formato pasado, ya que es el menos específico.

-

En códigos más viejo, encontrara text/unicode o el tipo Text.Estos equivalen text/plain,que guardara y recibia los datos del texto plano en ese lugar.

- -

Los enlaces deben incluir los datos de los dos tipos, el primero debe ser  URL utilizando el tipo text/uri-list,y el segundo es URL utilizando el tipo text/plain. Ambos tipos deben utilizar los mismos datos, la URL del enlace. Por ejemplo:

-
var dt = event.dataTransfer;
-dt.setData("text/uri-list", "http://www.mozilla.org");
-dt.setData("text/plain", "http://www.mozilla.org");
-
-

Es constumbre, establecer el tipo text/plain de ultimo, , ya que es menos específico que el tipo de URI.

-

Note que el tipo de URL uri-list es con una "i", no una "L"

-

Note that the URL type is uri-list with an 'I', not with an 'L'.

-

To drag multiple links, you can also separate each link with a linebreak. A line that begins with a number sign (#) is a comment and should not be considered a valid URL. You can use a comment to indicate the purpose of a link, or to hold the title associated with a link. The text/plain version of the drag data should include all links but should not include the comments.

-

For example:

-
http://www.mozilla.org
-#A second link
-http://www.xulplanet.com
-
-

This sample text/uri-list data contains two links and a comment.

-

When retrieving a dropped link, you should ensure you handle the case where multiple links may have been dragged, and any comments that appear in the data. For convenience, the special type URL may be used to refer to the first valid link within the data for the text/uri-list type. You should not add data using the URL type; attempting to do so will just set the value of the text/uri-list type instead.

-
var url = event.dataTransfer.getData("URL");
-
-

You may also see data using the text/x-moz-url type which is a Mozilla specific type. If it appears, it should be used before the text/uri-list type. It holds the URL of the link followed by the title of the link, separated by a linebreak. For example:

-
http://www.mozilla.org
-Mozilla
-http://www.xulplanet.com
-XUL Planet
-
-

Dragging HTML and XML

-

HTML content may use the text/html type. The data for this type should be the serialized HTML to drag. For instance, it would be suitable to set the data value for this type to the value of the innerHTML property of an element.

-

XML content may use the text/xml type, but you should ensure that the data value is well-formed XML.

-

You may also include a plain text representation of the HTML or XML data using the text/plain type. The data should be just the text and should not include any of the source tags or attributes. For instance:

-
var dt = event.dataTransfer;
-dt.setData("text/html", "Hello there, <strong>stranger</strong>");
-dt.setData("text/plain", "Hello there, stranger");
-
-

Dragging Files

-

A local file is dragged using the application/x-moz-file type with a data value that is an nsIFile object. Non-privileged web pages are not able to retrieve or modify data of this type. Because a file is not a string, you must use the mozSetDataAt method to assign the data. Similarly, when retrieving the data, you must use the mozGetDataAt method.

-
event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
-
-

If possible, you may also include the file URL of the file using both the text/uri-list and/or text/plain types. These types should be added last so that the more specific application/x-moz-file type has higher priority.

-

Multiple files will be received during a drop as mutliple items in the data transfer. See Dragging and Dropping Multiple Items for more details about this.

-

The following example shows how to create an area for receiving dropped files:

-
<listbox ondragenter="return checkDrag(event)"
-         ondragover="return checkDrag(event)"
-         ondrop="doDrop(event)"/>
-
-<script>
-function checkDrag(event)
-{
-  return event.dataTransfer.types.contains("application/x-moz-file");
-}
-
-function doDrop(event)
-{
-  var file = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0);
-  if (file instanceof Components.interfaces.nsIFile)
-    event.currentTarget.appendItem(file.leafName);
-}
-</script>
-
-

In this example, the event returns false only if the data transfer contains the application/x-moz-file type. During the drop event, the data associated with the file type is retrieved, and the filename of the file is added to the listbox. Note that the instanceof operator is used here as the mozGetDataAt method will return an nsISupports that needs to be checked and converted into an nsIFile. This is also a good extra check in case someone made a mistake and added a non-file for this type.

-

Dragging Images

-

Direct image dragging is not commonly done. In fact, Mozilla does not support direct image dragging on Mac or Linux platforms. Instead, images are usually dragged only by their URLs. To do this, use the text/uri-list type as with other URL links. The data should be the URL of the image or a data URL if the image is not stored on a web site or disk. For more information about data URLs, see the data URL scheme.

-

As with other links, the data for the text/plain type should also contain the URL. However, a data URL is not usually as useful in a text context, so you may wish to exclude the text/plain data in this situation.

-

In chrome or other privileged code, you may also use the image/jpeg, image/png or image/gif types, depending on the type of image. The data should be an object which implements the nsIInputStream interface. When this stream is read, it should provide the data bits for the image, as if the image was a file of that type.

-

You should also include the application/x-moz-file type if the image is located on disk. In fact, this a common way in which image files are dragged.

-

It is important to set the data in the right order, from most specific to least specific. The image type such as image/jpeg should come first, followed by the application/x-moz-file type. Next, you should set the text/uri-list data and finally the text/plain data. For example:

-
var dt = event.dataTransfer;
-dt.mozSetDataAt("image/png", stream, 0);
-dt.mozSetDataAt("application/x-moz-file", file, 0);
-dt.setData("text/uri-list", imageurl);
-dt.setData("text/plain", imageurl);
-
-

Note that the mozGetDataAt method is used for non-text data. As some contexts may only include some of these types, it is important to check which type is made available when receiving dropped images.

-

Dragging Nodes

-

Nodes and elements in a document may be dragged using the application/x-moz-node type. This data for the type should be a DOM node. This allows the drop target to receive the actual node where the drag was started from. Note that callers from a different domain will not be able to access the node even when it has been dropped.

-

You should always include a plain text alternative for the node.

-

Dragging Custom Data

-

You can also use other types that you make up for custom purposes. You should strive to always include a plain text alternative unless that object being dragged is specific to a particular site or application. In this case, the custom type ensures that the data cannot be dropped elsewhere.

-

Dragging files to an operating system folder

-

There are cases in which you may want to add a file to an existing drag event session, and you may also want to write the file to disk when the drop operation happens over a folder in the operating system when your code receives notification of the target folder's location. This only works in extensions (or other privileged code) and the data flavor "application/moz-file-promise" should be used. The following sample offers an overview of this advanced case:

-
// currentEvent is a given existing drag operation event
-
-currentEvent.dataTransfer.setData("text/x-moz-url", URL);
-currentEvent.dataTransfer.setData("application/x-moz-file-promise-url", URL);
-currentEvent.dataTransfer.setData("application/x-moz-file-promise-filename", leafName);
-currentEvent.dataTransfer.mozSetDataAt('application/x-moz-file-promise',
-                  new dataProvider(success,error),
-                  0, Components.interfaces.nsISupports);
-
-function dataProvider(){}
-
-dataProvider.prototype = {
-  QueryInterface : function(iid) {
-    if (iid.equals(Components.interfaces.nsIFlavorDataProvider)
-                  || iid.equals(Components.interfaces.nsISupports))
-      return this;
-    throw Components.results.NS_NOINTERFACE;
-  },
-  getFlavorData : function(aTransferable, aFlavor, aData, aDataLen) {
-    if (aFlavor == 'application/x-moz-file-promise') {
-
-       var urlPrimitive = {};
-       var dataSize = {};
-
-       aTransferable.getTransferData('application/x-moz-file-promise-url', urlPrimitive, dataSize);
-       var url = new String(urlPrimitive.value.QueryInterface(Components.interfaces.nsISupportsString));
-       console.log("URL file orignal is = " + url);
-
-       var namePrimitive = {};
-       aTransferable.getTransferData('application/x-moz-file-promise-filename', namePrimitive, dataSize);
-       var name = new String(namePrimitive.value.QueryInterface(Components.interfaces.nsISupportsString));
-
-       console.log("target filename is = " + name);
-
-       var dirPrimitive = {};
-       aTransferable.getTransferData('application/x-moz-file-promise-dir', dirPrimitive, dataSize);
-       var dir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile);
-
-       console.log("target folder is = " + dir.path);
-
-       var file = Cc['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
-       file.initWithPath(dir.path);
-       file.appendRelativePath(name);
-
-       console.log("output final path is =" + file.path);
-
-       // now you can write or copy the file yourself...
-    }
-  }
-}
-
-

{{ languages( { "ja": "Ja/DragDrop/Recommended_Drag_Types" } ) }}

diff --git a/files/es/web/api/htmlcanvaselement/toblob/index.html b/files/es/web/api/htmlcanvaselement/toblob/index.html deleted file mode 100644 index 4759cd6250..0000000000 --- a/files/es/web/api/htmlcanvaselement/toblob/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: HTMLCanvasElement.toBlob() -slug: Web/API/HTMLCanvasElement/toBlob -translation_of: Web/API/HTMLCanvasElement/toBlob ---- -
-
-
{{APIRef("Canvas API")}}
-
-
- -

EL metodo HTMLCanvasElement.toBlob() crea un objeto {{domxref("Blob")}} que representa la imagen contenida en el canvas; este archivo puede ser cacheado en el disco oo guardado en la memoria a desicion del  user agent. Si la propiedad type no se especifica el tipo de la imagen será image/png. La imagen creada tiene una resolución de 96dpi.
- El tercer argumento es usado con las imagenes  image/jpeg para especificar la calidad de salida.

- -

Syntax

- -
void canvas.toBlob(callback, type, encoderOptions);
-
- -

Parameters

- -
-
callback
-
A callback function with the resulting {{domxref("Blob")}} object as a single argument.
-
type {{optional_inline}}
-
A {{domxref("DOMString")}} indicating the image format. The default type is image/png.
-
encoderOptions {{optional_inline}}
-
A {{jsxref("Number")}} between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored.
-
- -

Return value

- -

None.

- -

Examples

- -

Getting a file representing the canvas

- -

Once you have drawn content into a canvas, you can convert it into a file of any supported image format. The code snippet below, for example, takes the image in the {{HTMLElement("canvas")}} element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new {{HTMLElement("img")}} element to the document, whose source image is the one created using the canvas.

- -
var canvas = document.getElementById("canvas");
-
-canvas.toBlob(function(blob) {
-  var newImg = document.createElement("img"),
-      url = URL.createObjectURL(blob);
-
-  newImg.onload = function() {
-    // no longer need to read the blob so it's revoked
-    URL.revokeObjectURL(url);
-  };
-
-  newImg.src = url;
-  document.body.appendChild(newImg);
-});
-
- -

Note that here we're creating a PNG image; if you add a second parameter to the toBlob() call, you can specify the image type. For example, to get the image in JPEG format:

- -
 canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality
- -
-

A way to convert a canvas to an ico (Mozilla only)

- -

This uses -moz-parse to convert the canvas to ico. Windows XP doesn't support converting from PNG to ico, so it uses bmp instead. A download link is created by setting the download attribute. The value of the download attribute is the name it will use as the file name.

- -
var canvas = document.getElementById("canvas");
-var d = canvas.width;
-ctx = canvas.getContext("2d");
-ctx.beginPath();
-ctx.moveTo(d / 2, 0);
-ctx.lineTo(d, d);
-ctx.lineTo(0, d);
-ctx.closePath();
-ctx.fillStyle = "yellow";
-ctx.fill();
-
-function blobCallback(iconName) {
-  return function(b) {
-    var a = document.createElement("a");
-    a.textContent = "Download";
-    document.body.appendChild(a);
-    a.style.display = "block";
-    a.download = iconName + ".ico";
-    a.href = window.URL.createObjectURL(b);
-  }
-}
-canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
-              '-moz-parse-options:format=bmp;bpp=32');
-
- -

Save toBlob to disk with OS.File (chrome/add-on context only)

- -
-

This technique saves it to the desktop and is only useful in Firefox chrome context or add-on code as OS APIs are not present on web sites.

-
- -
var canvas = document.getElementById("canvas");
-var d = canvas.width;
-ctx = canvas.getContext("2d");
-ctx.beginPath();
-ctx.moveTo(d / 2, 0);
-ctx.lineTo(d, d);
-ctx.lineTo(0, d);
-ctx.closePath();
-ctx.fillStyle = "yellow";
-ctx.fill();
-
-function blobCallback(iconName) {
-  return function(b) {
-    var r = new FileReader();
-    r.onloadend = function () {
-    // r.result contains the ArrayBuffer.
-    Cu.import('resource://gre/modules/osfile.jsm');
-    var writePath = OS.Path.join(OS.Constants.Path.desktopDir,
-                                 iconName + '.ico');
-    var promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result),
-                                      {tmpPath:writePath + '.tmp'});
-    promise.then(
-      function() {
-        console.log('successfully wrote file');
-      },
-      function() {
-        console.log('failure writing file')
-      }
-    );
-  };
-  r.readAsArrayBuffer(b);
-  }
-}
-
-canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
-              '-moz-parse-options:format=bmp;bpp=32');
- -

Polyfill

- -

A low performance polyfill based on toDataURL.

- -
if (!HTMLCanvasElement.prototype.toBlob) {
- Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
-  value: function (callback, type, quality) {
-
-    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
-        len = binStr.length,
-        arr = new Uint8Array(len);
-
-    for (var i=0; i<len; i++ ) {
-     arr[i] = binStr.charCodeAt(i);
-    }
-
-    callback( new Blob( [arr], {type: type || 'image/png'} ) );
-  }
- });
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5.1')}}No change
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}[1]{{CompatGeckoDesktop('19')}}{{CompatIE(10)}}{{property_prefix("ms")}}{{CompatNo}}{{CompatNo}}[2]
Image quality parameter (jpeg){{CompatNo}}{{CompatGeckoDesktop('25')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("19")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
Image quality parameter (jpeg){{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
-
- -

[1] Chrome does not implement this feature yet. See bug 67587.

- -

[2] WebKit does not implement this feature yet. See {{WebKitBug("71270")}}.

- -

See also

- - diff --git a/files/es/web/api/mediasource/index.html b/files/es/web/api/mediasource/index.html deleted file mode 100644 index 2f5ff914c9..0000000000 --- a/files/es/web/api/mediasource/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: MediaSource -slug: Web/API/MediaSource -translation_of: Web/API/MediaSource ---- -

{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}

- -

El MediaSource interfaz representa un recurso de media en datos por un {{domxref("HTMLMediaElement")}} objeto. Un MediaSource objeto puede ser atribuido a un {{domxref("HTMLMediaElement")}} para ser reproducido por el usuario.

- -

Constructor

- -
-
{{domxref("MediaSource.MediaSource", "MediaSource()")}}
-
construye y retorna un MediaSource objeto sin asociar un recurso con buffers.
-
- -

Propiedades

- -

Inherits properties from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("MediaSource.sourceBuffers")}} {{readonlyInline}}
-
Returns a {{domxref("SourceBufferList")}} object containing the list of {{domxref("SourceBuffer")}} objects associated with this MediaSource.
-
{{domxref("MediaSource.activeSourceBuffers")}} {{readonlyInline}}
-
Returns a {{domxref("SourceBufferList")}} object containing a subset of the {{domxref("SourceBuffer")}} objects contained within {{domxref("SourceBuffers")}} — the list of objects providing the selected video track,  enabled audio tracks, and shown/hidden text tracks.
-
{{domxref("MediaSource.readyState")}} {{readonlyInline}}
-
Returns an enum representing the state of the current MediaSource, whether it is not currently attached to a media element (closed), attached and ready to receive {{domxref("SourceBuffer")}} objects (open), or attached but the stream has been ended via {{domxref("MediaSource.endOfStream()")}} (ended.)
-
{{domxref("MediaSource.duration")}}
-
Gets and sets the duration of the current media being presented.
-
- -
-
- -
-
- -

Methods

- -

Inherits properties from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("MediaSource.addSourceBuffer()")}}
-
Creates a new {{domxref("SourceBuffer")}} of the given MIME type and adds it to the MediaSource's {{domxref("SourceBuffers")}} list.
-
{{domxref("MediaSource.removeSourceBuffer()")}}
-
Removes the given {{domxref("SourceBuffer")}} from the {{domxref("SourceBuffers")}} list associated with this MediaSource object.
-
{{domxref("MediaSource.endOfStream()")}}
-
Signals the end of the stream.
-
-

Static methods

-
-
{{domxref("MediaSource.isTypeSupported()")}}
-
Returns a {{domxref("Boolean")}} value indicating if the given MIME type is supported by the current user agent — this is, if it can successfully create {{domxref("SourceBuffer")}} objects for that MIME type.
-
- -

Examples

- -

The following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. This example was written by Nick Desaulniers and can be viewed live here (you can also download the source for further investigation.)

- -
var video = document.querySelector('video');
-
-var assetURL = 'frag_bunny.mp4';
-// Need to be specific for Blink regarding codecs
-// ./mp4info frag_bunny.mp4 | grep Codec
-var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
-
-if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
-  var mediaSource = new MediaSource;
-  //console.log(mediaSource.readyState); // closed
-  video.src = URL.createObjectURL(mediaSource);
-  mediaSource.addEventListener('sourceopen', sourceOpen);
-} else {
-  console.error('Unsupported MIME type or codec: ', mimeCodec);
-}
-
-function sourceOpen (_) {
-  //console.log(this.readyState); // open
-  var mediaSource = this;
-  var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
-  fetchAB(assetURL, function (buf) {
-    sourceBuffer.addEventListener('updateend', function (_) {
-      mediaSource.endOfStream();
-      video.play();
-      //console.log(mediaSource.readyState); // ended
-    });
-    sourceBuffer.appendBuffer(buf);
-  });
-};
-
-function fetchAB (url, cb) {
-  console.log(url);
-  var xhr = new XMLHttpRequest;
-  xhr.open('get', url);
-  xhr.responseType = 'arraybuffer';
-  xhr.onload = function () {
-    cb(xhr.response);
-  };
-  xhr.send();
-};
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#mediasource', 'MediaSource')}}{{Spec2('Media Source Extensions')}}Initial definition.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{CompatGeckoDesktop("25.0")}}[1]
- {{CompatGeckoDesktop("42.0")}}
11[2]158
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4.4 -

{{CompatNo}}

-
{{CompatNo}}1130{{CompatNo}}
-
- -

[1] Available after switching the about:config preference media.mediasource.enabled to true. In addition, support was limited to a whitelist of sites, for example YouTube, Netflix, and other popular streaming sites. The whitelist was removed and Media Source Extensions was enabled by default in 42+ for all sites.

- -

[2] Only works on Windows 8+.

- -

See also

- - diff --git a/files/es/web/api/webvtt_api/index.html b/files/es/web/api/webvtt_api/index.html deleted file mode 100644 index 7a54969a31..0000000000 --- a/files/es/web/api/webvtt_api/index.html +++ /dev/null @@ -1,903 +0,0 @@ ---- -title: Formato de pistas de texto para la web (WebVTT) -slug: Web/API/WebVTT_API -translation_of: Web/API/WebVTT_API ---- -
{{DefaultAPISidebar("WebVTT")}}
- -

El formato de pistas de texto para la web (WebVTT) es un formato para mostrar pistas de texto en le tiempo (como subtítulos) usando el elemento {{HTMLElement("track")}}. El propósito principal de los archivos de WebVTT es superponer pistas de texto a un elemento {{HTMLElement("video")}}. WebVTT es un formato basado en el texto, que debe de ser codificado usando {{Glossary("UTF-8")}}. Donde puedes usar espacios también puedes usar tabulaciones. También hay una pequeña API disponible para representar y manejar estas pistas de texto y los datos necesarios para realizar la reproducción del texto en los momentos correctos.

- -

Archivos WebVTT

- -

El tipo MIME de los archivos WebVTT es text/vtt.

- -

Un archivo WebVTT (.vtt) contiene apuntes, que pueden ser tanto de una línea como de varias, como se muestra debajo:

- -
WEBVTT
-
-00:01.000 --> 00:04.000
-- Nunca bebas nitrógeno líquido.
-
-00:05.000 --> 00:09.000
-- Podría perforar tu estómago.
-- Podrías morir.
-
-NOTE Esta es la última línea en el archivo
-
- -

Estructura WebVTT

- -

La estructura de un archivo WevWTT consiste de los siguientes componentes, algunos de ellos opcionales, en este orden:

- - - -
Ejemplo 1 - El archivo WebVTT más simple posible
- -
WEBVTT
-
- -
Ejemplo 2 - Archivo WebVTT muy simple con un encabezado de texto
- -
WEBVTT - Este archivo no tiene anotaciones.
-
- -
Ejemplo 3 - Ejemplo de un archivo WebVTT común con encabezado y anotaciones
- -
WEBVTT - Este archivo tiene anotaciones.
-
-14
-00:01:14.815 --> 00:01:18.114
-- ¿Qué?
-- ¿Dónde estamos ahora?
-
-15
-00:01:18.171 --> 00:01:20.991
-- Este es el país de los murciélagos grandes.
-
-16
-00:01:21.058 --> 00:01:23.868
-- [ Murciélagos chillando ]
-- Ellos no se pondrán entu pelo. Ellos están persiguiendo a los bichos.
-
- -

Estructura interna de un archivo WebVTT

- -

Vamos a reexaminar uno de nuestros ejemplos previos, y mirar la estructura de las anotaciones con un poco más de detalle.

- -
WEBVTT
-
-00:01.000 --> 00:04.000
-- Nunca bebas nitrógeno líquido.
-
-00:05.000 --> 00:09.000
-- Podría perforar tu estómago.
-- Podrías morir.
-
-NOTE Esta es la última línea en el archivo
- -

En el caso de cada anotación:

- - - -

También podemos poner comentarios en nuestro archivo .vtt, para ayudarnos a recorddar información importante sobre las partes de nuestro archivo. Estas deben estar en líneas separadas empezando con la cadena NOTE. Aprenderas más sobre eso en la siguiente sección.

- -

Es importante no usar líneas en blanco extras dentro de una anotación, por ejemplo entre las líneas de tiempo y las anotaciones. WebVTT está basado en líneas, una línea en blanco finalizará la anotación.

- -

Comentarios en WebVTT

- -

Los comentarios son un componente opcional que se puede usar para añadir informacion a un archivo WebVTT. Los comentarios estan pensados para aquellos que leen el archivo y no se muestran con las pistas de texto. Los comentarios pueden contener saltos de línea pero no una línea en blanco, que es equivalente a dos saltos de línea consecutivos. Una línea en blanco indica el fin de un comentario.

- -

Un comentario no puede contener la cadena de texto "-->", el símbolo &, o el signo de menor que (<). Si quisieses usar esos caracteres necesitarías hacer un escape usando por ejemplo &amp; para el símbolo &, y &lt; para menor que (<). Tambien es recomendado que uses la secuencia de escape de mayor que &gt; en vez de el simbo de mayor que (>) para evitar la confusión con etiquetas.

- -

Un comentario consiste en tres partes:

- - - -
Ejemplo 4 - Ejemplo común de WebVTT
- -
NOTE Esto es un comentario
-
- -
Ejemplo 5 - Comentario multilínea
- -
NOTE
-Un comentario que está ocupando
-más de una línea.
-
-NOTE También puedes hacer un comentario
-que ocupe más de una línea de esta manera.
-
- -
Ejemplo 6 - Uso común de comentarios
- -
WEBVTT - Traducción de la película que me gusta
-
-NOTE
-Esta traducción esta hecha por Kyle para que
-Algunos amigos puedan verla con sus padres.
-
-1
-00:02:15.000 --> 00:02:20.000
-- Ta en kopp varmt te.
-- Det är inte varmt.
-
-2
-00:02:20.000 --> 00:02:25.000
-- Har en kopp te.
-- Det smakar som te.
-
-NOTE Esta ultima línea puede no estar bien traducida.
-
-3
-00:02:25.000 --> 00:02:30.000
-- Ta en kopp
-
- -

Estilizando anotaciones WebVTT

- -

Tu puedes estilizar anotaciones WebVTT buscado elementos que coincidan con el pseudoelemento {{cssxref("::cue")}}.

- -

Dentro del CSS del sitio

- -
video::cue {
-  background-image: linear-gradient(to bottom, dimgray, lightgray);
-  color: papayawhip;
-}
-
-video::cue(b) {
-  color: peachpuff;
-}
-
- -

Aquí, todos los elementos de video estan estilizados para usar un gradiente gris como fondo, con "papayawhip" como color principal. Además el texto en negrita usando el elemento {{HTMLElement("b")}} tiene el color "peachpuff".

- -

El ejemplo HTML de abajo actualemte se encarga de mostrar los archivos multimedia él solo.

- -
<video controls autoplay src="video.webm">
- <track default src="track.vtt">
-</video>
-
- -

Within the WebVTT file itself

- -

You can also define the style directly in the WebVTT file. In this case, you insert your CSS rules into the file with each rule preceded by the string "STYLE" all by itelf on a line of text, as shown below:

- -
WEBVTT
-
-STYLE
-::cue {
-  background-image: linear-gradient(to bottom, dimgray, lightgray);
-  color: papayawhip;
-}
-/* Style blocks cannot use blank lines nor "dash dash greater than" */
-
-NOTE comment blocks can be used between style blocks.
-
-STYLE
-::cue(b) {
-  color: peachpuff;
-}
-
-00:00:00.000 --> 00:00:10.000
-- Hello <b>world</b>.
-
-NOTE style blocks cannot appear after the first cue.
- -

We can also use identifiers inside WebVTT file, which can be used for defining a new style for some particular cues in the file. The example where we wanted the transcription text to be red highlighted and the other part to remain normal, we can define it as follows using CSS. Where it must be noted that the CSS uses escape sequences the way they are used in HTML pages:

- -
WEBVTT
-
-1
-00:00.000 --> 00:02.000
-That’s an, an, that’s an L!
-
-crédit de transcription
-00:04.000 --> 00:05.000
-Transcrit par Célestes™
-
- -
::cue(#\31) { color: lime; }
-::cue(#crédit\ de\ transcription) { color: red; }
- -

Positioning of text tracks is also supported, by including positioning information after the timings in a cue, as seen below (see {{anch("Cue settings")}} for more information):

- -
WEBVTT
-
-00:00:00.000 --> 00:00:04.000 position:10%,line-left align:left size:35%
-Where did he go?
-
-00:00:03.000 --> 00:00:06.500 position:90% align:right size:35%
-I think he went down this lane.
-
-00:00:04.000 --> 00:00:06.500 position:45%,line-right align:center size:35%
-What are you waiting for?
- -

WebVTT cues

- -

A cue is a single subtitle block that has a single start time, end time, and textual payload. Example 6 consists of the header, a blank line, and then five cues separated by blank lines. A cue consists of five components:

- - - -
Example 7 - Example of a cue
- -
1 - Title Crawl
-00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
-Some time ago in a place rather distant....
- -

Cue identifier

- -

The identifier is a name that identifies the cue. It can be used to reference the cue from a script. It must not contain a newline and cannot contain the string "-->". It must end with a single newline. They do not have to be unique, although it is common to number them (e.g., 1, 2, 3, ...).

- -
Example 8 - Cue identifier from Example 7
- -
1 - Title Crawl
- -
Example 9 - Common usage of identifiers
- -
WEBVTT
-
-1
-00:00:22.230 --> 00:00:24.606
-This is the first subtitle.
-
-2
-00:00:30.739 --> 00:00:34.074
-This is the second.
-
-3
-00:00:34.159 --> 00:00:35.743
-Third
-
- -

Cue timings

- -

A cue timing indicates when the cue is shown. It has a start and end time which are represented by timestamps. The end time must be greater than the start time, and the start time must be greater than or equal to all previous start times. Cues may have overlapping timings.

- -

If the WebVTT file is being used for chapters ({{HTMLElement("track")}} {{htmlattrxref("kind")}} is chapters) then the file cannot have overlapping timings.

- -

Each cue timing contains five components:

- - - -

The timestamps must be in one of two formats:

- - - -

Where the components are defined as follows:

- - - -
Example 10 - Basic cue timing examples
- -
00:00:22.230 --> 00:00:24.606
-00:00:30.739 --> 00:00:34.074
-00:00:34.159 --> 00:00:35.743
-00:00:35.827 --> 00:00:40.122
- -
Example 11 - Overlapping cue timing examples
- -
00:00:00.000 --> 00:00:10.000
-00:00:05.000 --> 00:01:00.000
-00:00:30.000 --> 00:00:50.000
- -
Example 12 - Non-overlapping cue timing examples
- -
00:00:00.000 --> 00:00:10.000
-00:00:10.000 --> 00:01:00.581
-00:01:00.581 --> 00:02:00.100
-00:02:01.000 --> 00:02:01.000
- -

Cue settings

- -

Cue settings are optional components used to position where the cue payload text will be displayed over the video. This includes whether the text is displayed horizontally or vertically. There can be zero or more of them, and they can be used in any order so long as each setting is used no more than once.

- -

The cue settings are added to the right of the cue timings. There must be one or more spaces between the cue timing and the first setting and between each setting. A setting's name and value are separated by a colon. The settings are case sensitive so use lower case as shown. There are five cue settings:

- - - -
Example 13 - Cue setting examples
- -

The first line demonstrates no settings. The second line might be used to overlay text on a sign or label. The third line might be used for a title. The last line might be used for an Asian language.

- -
00:00:05.000 --> 00:00:10.000
-00:00:05.000 --> 00:00:10.000 line:63% position:72% align:start
-00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
-00:00:05.000 --> 00:00:10.000 vertical:rt line:-1 align:end
-
- -

Cue payload

- -

The payload is where the main information or content is located. In normal usage the payload contains the subtitles to be displayed. The payload text may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a cue.

- -

A cue text payload cannot contain the string "-->", the ampersand character (&), or the less-than sign (<). Instead use the escape sequence "&amp;" for ampersand and "&lt;" for less-than. It is also recommended that you use the greater-than escape sequence "&gt;" instead of the greater-than character (>) to avoid confusion with tags. If you are using the WebVTT file for metadata these restrictions do not apply.

- -

In addition to the three escape sequences mentioned above, there are fours others. They are listed in the table below.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 6 - Escape sequences
NameCharacterEscape Sequence
Ampersand&&amp;
Less-than<&lt;
Greater-than>&gt;
Left-to-right mark&lrm;
Right-to-left mark&rlm;
Non-breaking space &nbsp;
- -

Cue payload text tags

- -

There are a number of tags, such as <bold>, that can be used. However, if the WebVTT file is used in a {{HTMLElement("track")}} element where the attribute {{htmlattrxref("kind")}} is chapters then you cannot use tags.

- - - -

The following tags are the HTML tags allowed in a cue and require opening and closing tags (e.g., <b>text</b>).

- - - -

Interfaces

- -

There are two interfaces or APIs used in WebVTT which are:

- -

VTTCue interface

- -

It is used for providing an interface in Document Object Model API, where different attributes supported by it can be used to prepare and alter the cues in number of ways.

- -

Constructor is the first point for starting the Cue which is defined using the default constructor VTTCue(startTime, endTime, text) where starting time, ending time and text for cue can be adjusted. After that we can set the region for that particular cue to which this cue belongs using cue.region. Vertical, horizontal, line, lineAlign, Position, positionAlign, text, size and Align can be used to alter the cue and its formation, just like we can alter the objects form, shape and visibility in HTML using CSS. But the VTTCue interface is within the WebVTT provides the vast range of adjustment variables which can be used directly to alter the Cue. Following interface can be used to expose WebVTT cues in DOM API:

- -
enum AutoKeyword { "auto" };
-enum DirectionSetting { "" /* horizontal */, "rl", "lr" };
-enum LineAlignSetting { "start", "center", "end" };
-enum PositionAlignSetting { "line-left", "center", "line-right", "auto" };
-enum AlignSetting { "start", "center", "end", "left", "right" };
-[Constructor(double startTime, double endTime, DOMString text)]
-interface VTTCue : TextTrackCue {
-  attribute VTTRegion? region;
-  attribute DirectionSetting vertical;
-  attribute boolean snapToLines;
-  attribute (double or AutoKeyword) line;
-  attribute LineAlignSetting lineAlign;
-  attribute (double or AutoKeyword) position;
-  attribute PositionAlignSetting positionAlign;
-  attribute double size;
-  attribute AlignSetting align;
-  attribute DOMString text;
-  DocumentFragment getCueAsHTML();
-};
- -

VTT Region interface

- -

This is the second interface in WebVTT API.

- -

The new keyword can be used for defining a new VTTRegion object which can then be used for containing the multiple cues. There are several properties of VTTRegion which are width, lines, regionAnchorX, RegionAnchorY, viewportAnchorX, viewportAnchorY and scroll that can be used to specify the look and feel of this VTT region. The interface code is given below which can be used to expose the WebVTT regions in DOM API:

- -
enum ScrollSetting { "" /* none */, "up" };
-[Constructor]
-interface VTTRegion {
-  attribute double width;
-  attribute long lines;
-  attribute double regionAnchorX;
-  attribute double regionAnchorY;
-  attribute double viewportAnchorX;
-  attribute double viewportAnchorY;
-  attribute ScrollSetting scroll;
-};
- -

Methods and properties

- -

The methods used in WebVTT are those which are used to alter the cue or region as the attributes for both interfaces are different. We can categorize them for better understanding relating to each interface in WebVTT:

- - - -

Tutorial on how to write a WebVTT file

- -

There are few steps that can be followed to write a simple webVTT file. Before start, it must be noted that you can make use of a notepad and then save the file as ‘.vtt’ file. Steps are given below:

- -
    -
  1. Open a notepad.
  2. -
  3. The first line of WebVTT is standardized similar to the way some other languages require you to put headers as the file starts to indicate the file type. On the very first line you have to write:
  4. -
- -
WEBVTT
- -

      3. Leave the second line blank, and on the third line the time for first cue is to be specified. For example, for a first cue starting at time 1 second and ending at 5 seconds, it is written as:

- -
00:01.000 --> 00:05.000
- -
    -
  1. On the next line you can write the caption for this cue which will run from 1st second to the 5th second, inclusive.
  2. -
  3. Following the similar steps, a complete WebVTT file for specific video or audio file can be made.
  4. -
- -

CSS pseudo-classes

- -

CSS pseudo classes allow us to classify the type of object which we want to differentiate from other types of objects. It works in similar manner in WebVTT files as it works in HTML file.

- -

It is one of the good features supported by WebVTT is the localization and use of class elements which can be used in same way they are used in HTML and CSS to classify the style for particular type of objects, but here these are used for styling and classifying the Cues as shown below:

- -
WEBVTT
-
-04:02.500 --> 04:05.000
-J’ai commencé le basket à l'âge de 13, 14 ans
-
-04:05.001 --> 04:07.800
-Sur les <i.foreignphrase><lang en>playground</lang></i>, ici à Montpellier
- -

In the above example it can be observed that we can use the identifier and pseudo class name for defining the language of caption, where <i> tag is for italics.

- -

The type of pseudo class is determined by the selector it is using and working is similar in nature as it works in HTML. Following CSS pseudo classes can be used:

- - - -

Where p and a are the tags which are used in HTML for paragraph and link, respectively and they can be replaced by identifiers which are used for Cues in WebVTT file.

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("WebVTT")}}{{Spec2("WebVTT")}}Initial definition
- -

Browser compatibility

- -

VTTCue interface

- -
- - -

{{Compat("api.VTTCue", 0)}}

- -

TextTrack interface

- -
- - -

{{Compat("api.TextTrack", 0)}}

- -

Notes

-
-
- -

Prior to Firefox 50, the AlignSetting enum (representing possible values for {{domxref("VTTCue.align")}}) incorrectly included the value "middle" instead of "center". This has been corrected.

- -

WebVTT was implemented in Firefox 24 behind the preference {{pref("media.webvtt.enabled")}}, which is disabled by default; you can enable it by setting this preference to true. WebVTT is enabled by default starting in Firefox 31 and can be disabled by setting the preference to false.

- -

Prior to Firefox 58, the REGION keyword was creating {{domxref("VTTRegion")}} objects, but they were not being used. Firefox 58 now fully supports VTTRegion and its use; however, this feature is disabled by default behind the preference media.webvtt.regions.enabled; set it to true to enable region support in Firefox 58. Regions are enabled by default starting in Firefox 59 (see bugs {{bug(1338030)}} and {{bug(1415805)}}).

diff --git a/files/es/web/api/window/domcontentloaded_event/index.html b/files/es/web/api/window/domcontentloaded_event/index.html deleted file mode 100644 index 0659abde6f..0000000000 --- a/files/es/web/api/window/domcontentloaded_event/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: DOMContentLoaded -slug: Web/API/Window/DOMContentLoaded_event -translation_of: Web/API/Window/DOMContentLoaded_event -original_slug: Web/Events/DOMContentLoaded ---- -

El evento DOMContentLoaded es disparado cuando el documento HTML ha sido completamente cargado y parseado, sin esperar hojas de estilo, images y subframes para  finalizar la carga. Un evento muy diferente - load - debería ser usado solo para detectar una carga completa de la página. Es un error increíblemente popular usar load cuando DOMContentLoaded sería mucho más apropiado, así que úsalo con cuidado.

- -

JavaScript síncrono pausa el parseo del DOM.

- -

También hay mucho propósito general y bibliotecas autónomas que ofrecen métodos de navegador cruzado para detectar que el DOM está preparado.

- -

Speeding up

- -

If you want DOM to get parsed as fast as possible after the user had requested the page, some things you could do is turn your JavaScript asynchronous and to optimize loading of stylesheets which if used as usual, slow down page load due to being loaded in parallel, "stealing" traffic from the main html document.

- -

General info

- -
-
Specification
-
HTML5
-
Interface
-
Event
-
Bubbles
-
Yes
-
Cancelable
-
Yes (although specified as a simple event that isn't cancelable)
-
Target
-
Document
-
Default Action
-
None.
-
- -

Properties

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
- -

Example

- -
<script>
-  document.addEventListener("DOMContentLoaded", function(event) {
-    console.log("DOM fully loaded and parsed");
-  });
-</script>
-
- -
<script>
-  document.addEventListener("DOMContentLoaded", function(event) {
-    console.log("DOM fully loaded and parsed");
-  });
-
-for(var i=0; i<1000000000; i++)
-{} // this synchronous script is going to delay parsing of the DOM. So the DOMContentLoaded event is going to launch later.
-</script>
-
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0[1]{{CompatGeckoDesktop("1")}}[1]9.0[2]9.03.1[1]
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoMobile("1")}}[1]{{CompatUnknown}}[2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
-
- -

[1] Bubbling for this event is supported by at least Gecko 1.9.2, Chrome 6, and Safari 4.

- -

[2] Internet Explorer 8 supports the readystatechange event, which can be used to detect when the DOM is ready. In earlier versions of Internet Explorer, this state can be detected by repeatedly trying to execute document.documentElement.doScroll("left");, as this snippet will throw an error until the DOM is ready.

- - - - diff --git a/files/es/web/api/worker/postmessage/index.html b/files/es/web/api/worker/postmessage/index.html deleted file mode 100644 index c47fe400fc..0000000000 --- a/files/es/web/api/worker/postmessage/index.html +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: Worker.postMessage() -slug: Web/API/Worker/postMessage -translation_of: Web/API/Worker/postMessage ---- -

{{APIRef("Web Workers API")}}

- -

Web Workers API posee un metodo llamado postMessage() el cual envia un mensaje al ambito del worker. Este metodo acepta un parametro, el cual es un dato enviado al worker. El dato puede ser un valor o objeto controlado por el algoritmo strctured clone (incluye referencias ciclicas).

- -

El Worker puede enviar de vuelta información al hilo que lo genero usando el metodo {{domxref("DedicatedWorkerGlobalScope.postMessage")}}.

- -

Syntax

- -
myWorker.postMessage(aMessage, transferList);
- -

Parameters

- -
-
aMessage
-
The object to deliver to the worker; this will be in the data field in the event delivered to the {{domxref("DedicatedWorkerGlobalScope.onmessage")}} handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
-
transferList {{optional_inline}}
-
An optional array of {{domxref("Transferable")}} objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the worker it was sent to.
-
Only {{domxref("MessagePort")}} and {{domxref("ArrayBuffer")}} objects can be transferred.
-
- -

Returns

- -

Void.

- -

Example

- -

The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor. When either of two form inputs (first and second) have their values changed, {{event("change")}} events invoke postMessage() to send the value of both inputs to the current worker.

- -
var myWorker = new Worker("worker.js");
-
-first.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
-
-second.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
-
- -

For a full example, see ourBasic dedicated worker example (run dedicated worker).

- -
-

Note: postMessage() can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.

-
- -

Transfer Example

- -

This example is of a Firefox addon that transfers an ArrayBuffer from the main thread to the ChromeWorker, and then the ChromeWorker trasnfers it back to the main thread.

- -

Main thread code:

- -
var myWorker = new ChromeWorker(self.path + 'myWorker.js');
-
-function handleMessageFromWorker(msg) {
-    console.log('incoming message from worker, msg:', msg);
-    switch (msg.data.aTopic) {
-        case 'do_sendMainArrBuff':
-            sendMainArrBuff(msg.data.aBuf)
-            break;
-        default:
-            throw 'no aTopic on incoming message to ChromeWorker';
-    }
-}
-
-myWorker.addEventListener('message', handleMessageFromWorker);
-
-// Ok lets create the buffer and send it
-var arrBuf = new ArrayBuffer(8);
-console.info('arrBuf.byteLength pre transfer:', arrBuf.byteLength);
-
-myWorker.postMessage(
-    {
-        aTopic: 'do_sendWorkerArrBuff',
-        aBuf: arrBuf // The array buffer that we passed to the transferrable section 3 lines below
-    },
-    [
-        arrBuf // The array buffer we created 9 lines above
-    ]
-);
-
-console.info('arrBuf.byteLength post transfer:', arrBuf.byteLength);
-
- -

Worker code

- -
self.onmessage = function (msg) {
-    switch (msg.data.aTopic) {
-        case 'do_sendWorkerArrBuff':
-                sendWorkerArrBuff(msg.data.aBuf)
-            break;
-        default:
-            throw 'no aTopic on incoming message to ChromeWorker';
-    }
-}
-
-function sendWorkerArrBuff(aBuf) {
-    console.info('from worker, PRE send back aBuf.byteLength:', aBuf.byteLength);
-
-    self.postMessage({aTopic:'do_sendMainArrBuff', aBuf:aBuf}, [aBuf]);
-
-    console.info('from worker, POST send back aBuf.byteLength:', aBuf.byteLength);
-}
-
- -

Output logged

- -
arrBuf.byteLength pre transfer: 8                              bootstrap.js:40
-arrBuf.byteLength post transfer: 0                             bootstrap.js:42
-
-from worker, PRE send back aBuf.byteLength: 8                  myWorker.js:5:2
-
-incoming message from worker, msg: message { ... }             bootstrap.js:20
-got back buf in main thread, aBuf.byteLength: 8                bootstrap.js:12
-
-from worker, POST send back aBuf.byteLength: 0                 myWorker.js:7:2
- -

We see that byteLength goes to 0 as it is trasnferred. To see a fully working example of this Firefox demo addon see here: GitHub :: ChromeWorker - demo-transfer-arraybuffer

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('Web Workers')}}Initial definition.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Internet Explorer does not support {{domxref("Transferable")}} objects.

- -

See also

- - diff --git a/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html b/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html deleted file mode 100644 index 28675abd79..0000000000 --- a/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: Solicitudes síncronas y asíncronas -slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests -translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests ---- -

XMLHttpRequest soporta solicitudes síncronas y asíncronas, pero la mas preferida es la asíncrona por razones de rendimiento

- -

Las solicitudes síncronas bloquean la ejecución del código, mientras se procesa la solicitud, dejando a la pantalla congelada y dando una experiencia de usuario poco agradable

- -

Peticiones asíncronas

- -

Si se utiliza XMLHttpRequest de forma asíncrona, recibirá una devolución de llamada cuando los datos se hayan recibido . Esto permite que el navegador continúe funcionando de forma normal mientras se procesa la solicitud.

- -

Ejemplo: Enviar un archivo a la consola

- -

Este es el uso más simple de la asíncronia XMLHttpRequest.

- -
var xhr = new XMLHttpRequest();
-xhr.open("GET", "/bar/foo.txt", true);
-xhr.onload = function (e) {
-  if (xhr.readyState === 4) {
-    if (xhr.status === 200) {
-      console.log(xhr.responseText);
-    } else {
-      console.error(xhr.statusText);
-    }
-  }
-};
-xhr.onerror = function (e) {
-  console.error(xhr.statusText);
-};
-xhr.send(null); 
- -

En la linea 2, el ultimo parametro de open() , especifica true para indicar que la solicitud se tratara de forma asíncrona

- -

Line 3 creates an event handler function object and assigns it to the request's onload attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 4, and if it is, and the HTTP status is 200, dumps the received content.  If an error occurred, an error message is displayed.

- -

Line 15 actually initiates the request.  The callback routine is called whenever the state of the request changes.

- -

Ejemplo: Creando una funcion estandar para leer archivos externos.

- -

In some cases you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

- -
function xhrSuccess () { this.callback.apply(this, this.arguments); }
-
-function xhrError () { console.error(this.statusText); }
-
-function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oReq = new XMLHttpRequest();
-  oReq.callback = fCallback;
-  oReq.arguments = Array.prototype.slice.call(arguments, 2);
-  oReq.onload = xhrSuccess;
-  oReq.onerror = xhrError;
-  oReq.open("get", sURL, true);
-  oReq.send(null);
-}
-
- -

Usage:

- -
function showMessage (sMsg) {
-  alert(sMsg + this.responseText);
-}
-
-loadFile("message.txt", showMessage, "New message!\n\n");
-
- -

The signature of the utility function loadFile declares (i) a target URL to read (via HTTP GET), (ii) a function to execute on successful completion of the XHR operation, and (iii) an arbitrary list of additional arguments that are "passed through" the XHR object to the success callback function.

- -

Line 1 declares a function invoked when the XHR operation completes successfully.  It, in turn, invokes the callback function specified in the invocation of the loadFile function (in this case, the function showMessage) which has been assigned to a property of the XHR object (Line 7). The additional arguments (if any) supplied to the invocation of function loadFile are "applied" to the running of the callback function.

- -

Line 3 declares a function invoked when the XHR operation fails to complete successfully.

- -

Line 7 stores on the XHR object the success callback function given as the second argument to loadFile.

- -

Line 8 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable oReq, passed to the success callback function xhrSuccess., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess.

- -

Line 9 designates the function xhrSuccess as the callback to be invoked when the onload event fires, that is, when the XHR sucessfully completes.  

- -

Line 10 designates the function xhrError as the callback to be invoked when the XHR requests fails to complete.

- -

Line 11 specifies true for its third parameter to indicate that the request should be handled asynchronously.

- -

Line 12 actually initiates the request.

- -

Example: using a timeout

- -

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

- -
function loadFile(sUrl, timeout, callback){
-
-    var args = arguments.slice(3);
-    var xhr = new XMLHttpRequest();
-    xhr.ontimeout = function () {
-        console.error("The request for " + url + " timed out.");
-    };
-    xhr.onload = function() {
-        if (xhr.readyState === 4) {
-            if (xhr.status === 200) {
-                callback.apply(xhr, args);
-            } else {
-                console.error(xhr.statusText);
-            }
-        }
-    };
-    xhr.open("GET", url, true);
-    xhr.timeout = timeout;
-    xhr.send(null);
-}
- -

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.

- -

Usage:

- -
function showMessage (sMsg) {
-  alert(sMsg + this.responseText);
-}
-
-loadFile("message.txt", 2000, showMessage, "New message!\n");
-
- -

Here, we're specifying a timeout of 2000 ms.

- -
-

Note: Support for timeout was added in {{Gecko("12.0")}}.

-
- -

Synchronous request

- -
Note: Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
- -

In rare cases, the use of a synchronous method is preferable to an asynchronous one.

- -

Example: HTTP synchronous request

- -

This example demonstrates how to make a simple synchronous request.

- -
var request = new XMLHttpRequest();
-request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
-request.send(null);
-
-if (request.status === 200) {
-  console.log(request.responseText);
-}
-
- -

Line 3 sends the request.  The null parameter indicates that no body content is needed for the GET request.

- -

Line 5 checks the status code after the transaction is completed.  If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

- -

Example: Synchronous HTTP request from a Worker

- -

One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker.

- -

example.html (the main page):

- -
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<title>MDN Example</title>
-<script type="text/javascript">
-  var worker = new Worker("myTask.js");
-  worker.onmessage = function(event) {
-    alert("Worker said: " + event.data);
-  };
-
-  worker.postMessage("Hello");
-</script>
-</head>
-<body></body>
-</html>
-
- -

myFile.txt (the target of the synchronous XMLHttpRequest invocation):

- -
Hello World!!
-
- -

myTask.js (the Worker):

- -
self.onmessage = function (event) {
-  if (event.data === "Hello") {
-    var xhr = new XMLHttpRequest();
-    xhr.open("GET", "myFile.txt", false);  // synchronous request
-    xhr.send(null);
-    self.postMessage(xhr.responseText);
-  }
-};
-
- -
Note: The effect, because of the use of the Worker, is however asynchronous.
- -

It could be useful in order to interact in background with the server or to preload some content. See Using web workers for examples and details.

- -

Adapting Sync XHR usecases to the Beacon API

- -

There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the window.onunload and window.onbeforeunload events.  The navigator.sendBeacon API can support these usecases typically while delivering a good UX.

- -

The following example (from the sendBeacon docs) shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.

- -
window.addEventListener('unload', logData, false);
-
-function logData() {
-    var client = new XMLHttpRequest();
-    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
-    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
-    client.send(analyticsData);
-}
-
- -

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

- -

The following example shows a theoretical analytics code pattern that submits data to a server using the by using the sendBeacon() method.

- -
window.addEventListener('unload', logData, false);
-
-function logData() {
-    navigator.sendBeacon("/log", analyticsData);
-}
-
- -

See also

- - - -

{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

diff --git a/files/es/web/css/@document/index.html b/files/es/web/css/@document/index.html deleted file mode 100644 index 8c1ead6ac3..0000000000 --- a/files/es/web/css/@document/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: '@document' -slug: Web/CSS/@document -translation_of: Web/CSS/@document ---- -
{{CSSRef}}{{SeeCompatTable}}
- -

The @document CSS at-rule restricts the style rules contained within it based on the URL of the document. It is designed primarily for user-defined style sheets, though it can be used on author-defined style sheets, too.

- -
@document url("https://www.example.com/") {
-  h1 {
-    color: green;
-  }
-}
-
- - - -

Syntax

- - - -

Una regla @document puede especificar una o más funciones coincidentes. Si alguna de las funciones se aplica a una URL determinada, la regla tendrá efecto en esa URL. Las funciones disponibles son:

- - - -

The values provided to the url(), url-prefix(), and domain() functions can be optionally enclosed by single or double quotes. The values provided to the regexp() function must be enclosed in quotes.

- -

Escaped values provided to the regexp() function must additionally be escaped from the CSS. For example, a . (period) matches any character in regular expressions. To match a literal period, you would first need to escape it using regular expression rules (to \.), then escape that string using CSS rules (to \\.).

- -
-

Note: There is a -moz-prefixed version of this property — @-moz-document. This has been limited to use only in user and UA sheets in Firefox 59 in Nightly and Beta — an experiment designed to mitigate potential CSS injection attacks ({{bug(1035091)}}).

-
- -

Formal syntax

- -{{csssyntax}} - -

Example

- -

CSS

- -
@document url(http://www.w3.org/),
-          url-prefix(http://www.w3.org/Style/),
-          domain(mozilla.org),
-          regexp("https:.*") {
-  /* CSS rules here apply to:
-     - The page "http://www.w3.org/"
-     - Any page whose URL begins with "http://www.w3.org/Style/"
-     - Any page whose URL's host is "mozilla.org"
-       or ends with ".mozilla.org"
-     - Any page whose URL starts with "https:" */
-
-  /* Make the above-mentioned pages really ugly */
-  body {
-    color: purple;
-    background: yellow;
-  }
-}
-
- -

Specifications

- -

Initially in {{SpecName('CSS3 Conditional')}}, @document has been postponed to Level 4.

- -

Browser compatibility

- - - -

{{Compat("css.at-rules.document")}}

- -

See also

- - diff --git a/files/es/web/css/background-position-x/index.html b/files/es/web/css/background-position-x/index.html deleted file mode 100644 index 16f74f3cb7..0000000000 --- a/files/es/web/css/background-position-x/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: background-position-x -slug: Web/CSS/background-position-x -translation_of: Web/CSS/background-position-x ---- -
{{CSSRef}}
- -

El background-position-x propiedad de CSS  coloca la posicion horizontal inicial por cada imagen de fondo. La posicion es relativa a la posicion de la capa puesta por {{cssxref("background-origin")}}.

- -
{{EmbedInteractiveExample("pages/css/background-position-x.html")}}
- - - -

The value of this property is overridden by any declaration of the {{cssxref("background")}} or {{cssxref("background-position")}} shorthand properties applied to the element after it.

- -

Syntax

- -
/* Keyword values */
-background-position-x: left;
-background-position-x: center;
-background-position-x: right;
-
-/* <percentage> values */
-background-position-x: 25%;
-
-/* <length> values */
-background-position-x: 0px;
-background-position-x: 1cm;
-background-position-x: 8em;
-
-/* Side-relative values */
-background-position-x: right 3px;
-background-position-x: left 25%;
-
-/* Multiple values */
-background-position-x: 0px, center;
-
-/* Global values */
-background-position-x: inherit;
-background-position-x: initial;
-background-position-x: unset;
-
- -

The background-position-x property is specified as one or more values, separated by commas.

- -

Values

- -
-
left
-
Aligns the left edge of the background image with the left edge of the background position layer.
-
center
-
Aligns the center of the background image with the center of the background position layer.
-
right
-
Aligns the right edge of the background image with the right edge of the background position layer.
-
{{cssxref("<length>")}}
-
The offset of the given background image's left vertical edge from the background position layer's left vertical edge. (Some browsers allow assigning the right edge for offset).
-
{{cssxref("<percentage>")}}
-
The offset of the given background image's horizontal position relative to the container. A value of 0% means that the left edge of the background image is aligned with the left edge of the container, and a value of 100% means that the right edge of the background image is aligned with the right edge of the container, thus a value of 50% horizontally centers the background image.
-
- -

Formal definition

- -

{{cssinfo}}

- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -

Basic example

- -

The following example shows a simple background image implementation, with background-position-x and background-position-y used to define the image's horizontal and vertical positions separately.

- -

HTML

- -
<div></div>
- -

CSS

- -
div {
-  width: 300px;
-  height: 300px;
-  background-color: skyblue;
-  background-image: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png);
-  background-repeat: no-repeat;
-  background-position-x: center;
-  background-position-y: bottom 10px;
-}
- -

Result

- -

{{EmbedLiveSample('Basic_example', '100%', 300)}}

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Backgrounds', '#background-position-longhands', 'background-position-x')}}{{Spec2('CSS4 Backgrounds')}}Initial specification of longhand sub-properties of {{cssxref("background-position")}} to match longstanding implementations.
- -

Browser compatibility

- -

{{Compat("css.properties.background-position-x")}}

- -

See also

- - diff --git a/files/es/web/css/border-radius/index.html b/files/es/web/css/border-radius/index.html deleted file mode 100644 index 39e3ab03d7..0000000000 --- a/files/es/web/css/border-radius/index.html +++ /dev/null @@ -1,320 +0,0 @@ ---- -title: border-radius -slug: Web/CSS/border-radius -tags: - - CSS - - CSS Borders - - CSS Property - - Reference -translation_of: Web/CSS/border-radius ---- -

{{ CSSRef() }}

- -

Resumen

- -

La propiedad CSS border-radius permite a los desarrolladores Web definir qué tan redondeadas serán las esquinas. La redondez de cada esquina está definida usando uno o dos valores para el radio que define su forma dependiendo si es un círculo o una elipse.

- -

Images of CSS3 rounded corners: no rounding, rounding w/ an arc of circle, rounding w/ an arc of ellipse

- -

El radio se aplica a todo el {{ Cssxref("background") }}, aun si el elemento no tiene bordes; la posición exacta del recorte es definida por la propiedad {{ Cssxref("background-clip") }}.

- -

Esta propiedad es un atajo para establecer las cuatro propiedades {{ Cssxref("border-top-left-radius") }}, {{ Cssxref("border-top-right-radius") }}, {{ Cssxref("border-bottom-right-radius") }} y {{ Cssxref("border-bottom-left-radius") }}.

- -
As with any shorthand property, individual inherited values are not possible, that is border-radius:0 0 inherit inherit, which would override existing definitions partially. In that case, the individual longhand properties have to be used.
- -

{{cssinfo}}

- -

Sintaxis

- -
Formal grammar: [ <length> | <percentage> ]{1,4}  [ / [ <length> | <percentage> ]{1,4}] ?
-                \------------------------------/      \-------------------------------/
-                           First radii                     Second radii (optional)
-
- -
The syntax of the first radius allows one to four values:
-border-radius: radius
-border-radius: top-left-and-bottom-right top-right-and-bottom-left
-border-radius: top-left top-right-and-bottom-left bottom-right
-border-radius: top-left top-right bottom-right bottom-left
-
-The syntax of the second radius also allows one to four values
-border-radius: (first radius values) / radius
-border-radius: (first radius values) / top-left-and-bottom-right top-right-and-bottom-left
-border-radius: (first radius values) / top-left top-right-and-bottom-left bottom-right
-border-radius: (first radius values) / top-left top-right bottom-right bottom-left
-
-border-radius: inherit
-
- -

Valores

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
radiusall-corner.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in each corner of the border. It is used only in the one-value syntax.
top-left-and-bottom-righttop-left-bottom-right.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-left and bottom-right corners of the element's box. It is used only in the two-value syntax.
top-right-and-bottom-lefttop-right-bottom-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-right and bottom-left corners of the element's box. It is used only in the two- and three-value syntaxes.
top-lefttop-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-left corner of the element's box. It is used only in the three- and four-value syntaxes.
top-righttop-right.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-right corner of the element's box. It is used only in the four-value syntax.
bottom-rightbottom-rigth.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the bottom-right corner of the element's box. It is used only in the three- and four-value syntaxes.
bottom-leftbottom-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the bottom-left corner of the element's box. It is used only in the four-value syntax.
inherit Is a keyword indicating that all four values are inherited from their parent's element calculated value.
- -

Valores

- -
-
<length>
-
Denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipsis. It can be expressed in any unit allowed by the CSS {{cssxref("<length>")}} data types. Negative values are invalid.
-
<percentage>
-
Denotes the size of the circle radius, or the semi-major and semi-minor axes of the ellipsis, using percentage values. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid.
-
- -

Por ejemplo:

- -
border-radius: 1em/5em;
-
-/* es equivalente a: */
-
-border-top-left-radius:     1em 5em;
-border-top-right-radius:    1em 5em;
-border-bottom-right-radius: 1em 5em;
-border-bottom-left-radius:  1em 5em;
-
- -
border-radius: 4px 3px 6px / 2px 4px;
-
-/* es equivalente a: */
-
-border-top-left-radius:     4px 2px;
-border-top-right-radius:    3px 4px;
-border-bottom-right-radius: 6px 2px;
-border-bottom-left-radius:  3px 4px;
-
- -

Ejemplos

- -
  border: solid 10px;
-  /* the border will curve into a 'D' */
-  border-radius: 10px 40px 40px 10px;
-
- -
  border: groove 1em red;
-  border-radius: 2em;
-
- -
  background: gold;
-  border: ridge gold;
-  border-radius: 13em/3em;
-
- -
  border: none;
-  border-radius: 40px 10px;
-
- -
  border: none;
-  border-radius: 50%;
-
- -

Notas

- - - -

Especificaciones

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds', '#border-radius', 'border-radius') }}{{ Spec2('CSS3 Backgrounds') }} 
- -

Compatibilidad con los navegadores

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{ CompatGeckoDesktop("2.0") }}
- {{ CompatGeckoDesktop("1.0") }}{{ property_prefix("-moz") }}
4.0
- 0.2{{ property_prefix("-webkit") }}
9.010.55.0
- 3.0{{ property_prefix("-webkit") }}
Elliptical borders{{ CompatGeckoDesktop("1.9.1") }}yesyesyesyes, but see below
4 values for 4 cornersyes4.0yesyes5.0
Percentagesyes
- was {{ non-standard_inline() }} (see below)
yesyes11.55.1
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureiOS SafariOpera MiniOpera MobileAndroid Browser
Basic support3.2{{ property_prefix("-webkit") }}{{ CompatNo() }}{{ CompatNo() }}2.1{{ property_prefix("-webkit") }}
Elliptical borders{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
4 values for 4 corners{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
Percentages{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
-
- -

<percentage> values

- - - -

Gecko notes

- -

In Gecko 2.0 -moz-border-radius was renamed to border-radius; -moz-border-radius was supported as an alias until Gecko 12.0. In order to conform to the CSS3 standard, Gecko 2.0

- - - -
Note: Support for the prefixed version (-moz-border-radius) was removed in Gecko 13.0 {{ geckoRelease("13.0") }}.
- -

WebKit notes

- -

Older Safari and Chrome versions (prior to WebKit 532.5)

- - - -

Opera notes

- -

In Opera (prior to Opera 11.60), applying border-radius to replaced elements will not have rounded corners.

- -

Vea también

- - - -

{{ languages( { "de": "de/CSS/border-radius", "fr": "fr/CSS/-moz-border-radius", "ja": "ja/CSS/border-radius", "pl": "pl/CSS/-moz-border-radius" } ) }}

diff --git a/files/es/web/css/cascade/index.html b/files/es/web/css/cascade/index.html deleted file mode 100644 index 87b99bd61c..0000000000 --- a/files/es/web/css/cascade/index.html +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Introducción a CSS en cascada -slug: Web/CSS/Cascade -translation_of: Web/CSS/Cascade ---- -
{{CSSRef}}
- -
La cascada es un algoritmo que define como combinar valores de propiedad originarios de diferentes fuentes. Este se encuentra en el núcleo de CSS, como enfatizafo por el nombre: Hojas de Estilo en Cascada. Este articulo explica que es cascada, el orden de las {{Glossary("CSS")}} declaraciones en cascada, y como esto te afecta, el desarrollador web.
- -

¿Cuáles entidades CSS participan en la cascada?

- -

Solo las declaraciones CSS, es decir pares de propiedad/valor, participan en la cascada. Esto significa que las at-rules que contienen entidades distintas de las declaraciones, como una regla @font-face que contiene descriptores, no participan en la cascada. En estos casos, solo la regla-at en su conjunto participa en la cascada: aquí, la @font-face identificada por su descriptor de familia de tipografías. Si se definen varias reglas @font-face con el mismo descriptor, solo se considera la @font-face, como conjunto, más adecuada. 

- -

Mientras que las declaraciones contenidas en la mayoría de las reglas-at -como aquellas en @media, @document o @support - participan en la cascada, las declaraciones contenidas en @keyframes no. Como con @font-face, solo la regla-at en su conjunto se selecciona a través del algoritmo en cascada.

- -

Finalmente, debemos tener en cuenta que {{cssxref ("@ import")}} y {{cssxref ("@ charset")}} obedecen a algoritmos específicos y no se ven afectados por el algoritmo en cascada.

- -

Origin of CSS declarations

- -

The CSS cascade algorithm's job is to select CSS declarations in order to determine the correct values for CSS properties. CSS declarations originate from different origins: the {{anch("User-agent stylesheets")}}, the {{anch("Author stylesheets")}}, and the {{anch("User stylesheets")}}.

- -

Though style sheets come from these different origins, they overlap in scope; to make this work, the cascade algorithm defines how they interact.

- -

User-agent stylesheets

- -

The browser has a basic style sheet that gives a default style to any document. These style sheets are named user-agent stylesheets. Some browsers use actual style sheets for this purpose, while others simulate them in code, but the end result is the same.

- -

Some browsers let users modify the user-agent stylesheet. Although some constraints on user-agent stylesheets are set by the HTML specification, browsers still have a lot of latitude: that means that significant differences exist from one browser to another. To simplify the development process, Web developers often use a CSS reset style sheet, forcing common properties values to a known state before beginning to make alterations to suit their specific needs.

- -

Author stylesheets

- -

Author stylesheets are the most common type of style sheet. These are style sheets that define styles as part of the design of a given web page or site. The author of the page defines the styles for the document using one or more stylesheets, which define the look and feel of the website — its theme.

- -

User stylesheets

- -

The user (or reader) of the web site can choose to override styles in many browsers using a custom user stylesheet designed to tailor the experience to the user's wishes.

- -

Cascading order

- -

The cascading algorithm determines how to find the value to apply for each property for each document element.

- -
    -
  1. It first filters all the rules from the different sources to keep only the rules that apply to a given element. That means rules whose selector matches the given element and which are part of an appropriate media at-rule.
  2. -
  3. Then it sorts these rules according to their importance, that is, whether or not they are followed by !important, and by their origin. The cascade is in ascending order, which means that !important values from a user-defined style sheet have precedence over normal values originated from a user-agent style sheet: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    OriginImportance
    1user agentnormal
    2usernormal
    3authornormal
    4animations
    5author!important
    6user!important
    7user agent!important
    8transitions
    -
  4. -
  5. In case of equality, the specificity of a value is considered to choose one or the other.
  6. -
- -

Resetting styles

- -

After your content has finished altering styles, it may find itself in a situation where it needs to restore them to a known state. This may happen in cases of animations, theme changes, and so forth. The CSS property {{cssxref("all")}} lets you quickly set (almost) everything in CSS back to a known state.

- -

all lets you opt to immediately restore all properties to any of their initial (default) state, the state inherited from the previous level of the cascade, a specific origin (the user-agent stylesheet, the author stylesheet, or the user stylesheet), or even to clear the values of the properties entirely.

- -

CSS animations and the cascade

- -

CSS animations, using {{ cssxref("@keyframes")}} at-rules, define animations between states. Keyframes don't cascade, meaning that at any given time CSS takes values from only one single {{cssxref("@keyframes")}}, and never mixes multiple ones together.

- -

When several keyframes are appropriate, it chooses the latest defined in the most important document, but never combined all together.

- -

Example

- -

Let's look at an example involving multiple sources of CSS across the various origins; here we have a user agent style sheet, two author style sheets, a user stylesheet, and inline styles within the HTML:

- -

User-agent CSS:

- -
li { margin-left: 10px }
- -

Author CSS 1:

- -
li { margin-left: 0 } /* This is a reset */
- -

Author CSS 2:

- -
@media screen {
-  li { margin-left: 3px }
-}
-
-@media print {
-  li { margin-left: 1px }
-}
-
- -

User CSS:

- -
.specific { margin-left: 1em }
- -

HTML:

- -
<ul>
-  <li class="specific">1<sup>st</sup></li>
-  <li>2<sup>nd</sup></li>
-</ul>
-
- -

In this case, declarations inside li and .specific rules should apply. No declaration is marked as !important, so the precedence order is author style sheets before user style sheets or user-agent stylesheet.

- -

So three declarations are in competition:

- -
margin-left: 0
- -
margin-left: 3px
- -
margin-left: 1px
- -

The last one is ignored (on a screen), and the first two have the same selector, hence the same specificity. Therefore, it is the last one that is then selected:

- -
margin-left: 3px
- -

Note that the declaration defined in the user CSS, though having a greater specificity, is not chosen as the cascade algorithm is applied before the specificity algorithm.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS4 Cascade")}}{{Spec2("CSS4 Cascade")}}Added the {{CSSxRef("revert")}} keyword, which allows rolling a property back a cascade level.
{{SpecName("CSS3 Cascade")}}{{Spec2("CSS3 Cascade")}}Removed the override cascade origin, as it was never used in a W3C standard.
{{SpecName("CSS2.1", "cascade.html", "the cascade")}}{{Spec2("CSS2.1")}}
{{SpecName("CSS1", "#the-cascade", "the cascade")}}{{Spec2("CSS1")}}Initial definition.
- -

See also

- - diff --git a/files/es/web/css/clip-path/index.html b/files/es/web/css/clip-path/index.html deleted file mode 100644 index a8b5253601..0000000000 --- a/files/es/web/css/clip-path/index.html +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: clip-path -slug: Web/CSS/clip-path -translation_of: Web/CSS/clip-path ---- -
{{CSSRef}}{{SeeCompatTable}}
- -

La propiedad CSS clip-path proviene que una porción de un elemento se muestre definiendo una región de recorte para mostrarse, es decir, solo una parte especifica del elemento se mostrara. La región recortada es un path especificado como una URL referenciando a un SVG inline o externo, o un metodo de figura como lo es circle(). La propiedad clip-path reemplaza la ahora deprecada propiedad clip.

- -
/* Valores clave */
-clip-path: none;
-
-/* Valores de imagen */
-clip-path: url(resources.svg#c1);
-
-/* Valores de caja */
-clip-path: fill-box;
-clip-path: stroke-box;
-clip-path: view-box;
-clip-path: margin-box;
-clip-path: border-box;
-clip-path: padding-box;
-clip-path: content-box;
-
-/* Valores geometricos */
-clip-path: inset(100px 50px);
-clip-path: circle(50px at 0 100px);
-clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
-
-/* Valores Geometricos y de caja combinados */
-clip-path: padding-box circle(50px at 0 100px);
-
-/* Valores globales */
-clip-path: inherit;
-clip-path: initial;
-clip-path: unset;
-
- -

{{cssinfo}}

- -

Syntax

- -

Valores

- -
-
url()
-
Represents a URL referencing a clip path element.
-
 
-
inset(), circle(), ellipse(), polygon()
-
A {{cssxref("<basic-shape>")}} function. Such a shape will make use of the specified <geometry-box> to size and position the basic shape. If no geometry box is specified, the border-box will be used as reference box.
-
<geometry-box>
-
If specified in combination with a <basic-shape>, it provides the reference box for the basic shape. If specified by itself, it uses the edges of the specified box including any corner shaping (e.g. defined by {{cssxref("border-radius")}}) as clipping path. The geometry box can be one of the following values: -
-
fill-box
-
Uses the object bounding box as reference box.
-
stroke-box
-
Uses the stroke bounding box as reference box.
-
view-box
-
Uses the nearest SVG viewport as reference box. If a {{SVGAttr("viewBox")}} attribute is specified for the element creating the SVG viewport, the reference box is positioned at the origin of the coordinate system established by the viewBox attribute and the dimension of the reference box is set to the width and height values of the viewBox attribute.
-
margin-box
-
Uses the margin box as the reference box.
-
border-box
-
Uses the border box as the reference box.
-
padding-box
-
Uses the padding box as the reference box.
-
content-box
-
Uses the content box as the reference box.
-
-
-
none
-
There is no clipping path created.
-
- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -
/* inline SVG  */
-.target {
-  clip-path: url(#c1);
-}
-
-/* external SVG */
-.anothertarget {
-  clip-path: url(resources.svg#c1);
-}
-
-/* circle */
-.circleClass {
-  clip-path: circle(15px at 20px 20px);
-}
- -

Live sample

- -

HTML

- -
<img id="clipped" src="https://mdn.mozillademos.org/files/12668/MDN.svg"
-    alt="MDN logo">
-<svg height="0" width="0">
-  <defs>
-    <clipPath id="cross">
-      <rect y="110" x="137" width="90" height="90"/>
-      <rect x="0" y="110" width="90" height="90"/>
-      <rect x="137" y="0" width="90" height="90"/>
-      <rect x="0" y="0" width="90" height="90"/>
-    </clipPath>
-  </defs>
-</svg>
-
-<select id="clipPath">
-  <option value="none">none</option>
-  <option value="circle(100px at 110px 100px)">circle</option>
-  <option value="url(#cross)" selected>cross</option>
-  <option value="inset(20px round 20px)">inset</option>
-</select>
-
- -

CSS

- -
#clipped {
-  margin-bottom: 20px;
-  clip-path: url(#cross);
-}
-
- - - -

Result

- -

{{EmbedLiveSample("Live_sample", 230, 250)}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS Masks", "#the-clip-path", 'clip-path')}}{{Spec2('CSS Masks')}}Extends its application to HTML elements
{{SpecName('SVG1.1', 'masking.html#ClipPathProperty', 'clip-path')}}{{Spec2('SVG1.1')}}Initial definition (applies to SVG elements only)
- -

Browser compatibility

- - - -

{{Compat("css.properties.clip-path")}}

- -

See also

- - diff --git a/files/es/web/css/media_queries/testing_media_queries/index.html b/files/es/web/css/media_queries/testing_media_queries/index.html deleted file mode 100644 index 81f1e41608..0000000000 --- a/files/es/web/css/media_queries/testing_media_queries/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Probando media queries -slug: Web/CSS/Media_Queries/Testing_media_queries -translation_of: Web/CSS/Media_Queries/Testing_media_queries -original_slug: Web/Guide/CSS/probando_media_queries ---- -

{{SeeCompatTable}}

-

El DOM proporciona características que hacen posible probar los resultados de un media query estructuradamente. Esto es hecho usando la interfaz {{domxref("MediaQueryList") }} y sus métodos y propiedades. Una vez que hayas creado el objeto {{domxref("MediaQueryList") }}, puedes revisar el resultado del query o, como alternativa, recibir notificaciones automáticamente cuando el resultado cambie.

-

Creando una media query list

-

Before you can evaluate the results of a query, you need to create the {{domxref("MediaQueryList") }} object representing the media query. To do this, use the {{domxref("window.matchMedia") }} method.

-

For example, if you want to set up a query list that determines whether the device is in landscape or portrait orientation, you can do so like this:

-
var mql = window.matchMedia("(orientation: portrait)");
-
-

Revisando el resultado de un query

-

Once your media query list has been created, you can check the result of the query by looking at the value of its matches property, which reflects the result of the query:

-
if (mql.matches) {
-  /* The device is currently in portrait orientation */
-} else {
-  /* The device is currently in landscape orientation */
-}
-
-

Recibiendo notificaciones query

-

If you need to be aware of changes to the evaluated result of the query on an ongoing basis, it's more efficient to register a listener than to poll the query's result. To do this, you can call the addListener() method on the {{domxref("MediaQueryList") }} object, specifying an observer that implements the {{domxref("MediaQueryListListener") }} interface:

-
var mql = window.matchMedia("(orientation: portrait)");
-mql.addListener(handleOrientationChange);
-handleOrientationChange(mql);
-
-

This code creates the orientation testing media query list, mql, then adds a listener to it. Note that after adding the listener, we actually invoke the listener directly once. This lets our listener perform initial adjustments based on the current device orientation (otherwise, if our code assumes the device is in portrait mode but it's actually in landscape mode at startup, we could have inconsistencies).

-

The handleOrientationChange() method we implement then would look at the result of the query and handle whatever we need to do on an orientation change:

-
function handleOrientationChange(mql) {
-  if (mql.matches) {
-    /* The device is currently in portrait orientation */
-  } else {
-    /* The device is currently in landscape orientation */
-  }
-}
-
-

Terminando con las notificaciones query 

-

Cuando ya no vayas a necesitar recibir las notificaciones sobre los cambios de valro de tu media query, simplemente llama al removeListener() en el {{domxref("MediaQueryList") }}:

-
mql.removeListener(handleOrientationChange);
-
-

Compatibilidad con los navegadores

-

{{CompatibilityTable}}

-
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico9{{CompatGeckoDesktop("6.0") }}1012.15.1
-
-
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico3.0{{CompatUnknown}}1012.15
-
-

Ver también

- diff --git a/files/es/web/html/attributes/autocomplete/index.html b/files/es/web/html/attributes/autocomplete/index.html deleted file mode 100644 index 553e9a293c..0000000000 --- a/files/es/web/html/attributes/autocomplete/index.html +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: The HTML autocomplete attribute -slug: Web/HTML/Attributes/autocomplete -translation_of: Web/HTML/Attributes/autocomplete -original_slug: Web/HTML/Atributos/autocomplete ---- -

El atributo autocomplete  está disponible en varios tipos de  {{HTMLElement("input")}} aquellos que toman un texto o valor numérico como entrada. autocomplete  permite a los desarrolladores web especificar qué permisos si los hay {{Glossary("user agent")}}  debe proporcionar asistencia automatizada para completar los valores de los campos de formulario, así como una guía para el navegador en cuanto al tipo de información que se espera en el campo.

- -

 

- -

Los valores sugeridos generalmente depende del navegador. Normalmente, provienen de valores ​​ingresados ​​por el usuario, pero también pueden provenir de valores preconfigurados. Por ejemplo, un navegador puede permitir que el usuario guarde su nombre, dirección, número de teléfono y direcciones de correo electrónico para autocompletar así como también datos de tarjetas de crédito.

- -

Si un elemento {{HTMLElement("input")}} no tiene el atributo autocomplete , entonces los navegadores usan el atributo autocomplete del {{HTMLElement("form")}} que lo contiene. En otras palabras, el {{HTMLElement("form")}} del que el {{HTMLElement("input")}} desciende. También puede ser especificado en el atributo {{htmlattrxref("form", "input")}} del {{HTMLElement("input")}} en cuestión.

- -

Para más información vea el atributo {{htmlattrxref("autocomplete", "form")}} del elemento {{HTMLElement("form")}}

- -
-

Para proveer el autocompletado, el navegador necesita del los elementos <input>:

- -
    -
  1. Que tengan name y/o id
  2. -
  3. Pertenezcan a un elemento <form>
  4. -
  5. Que el formulario tenga un botón {{HTMLElement("input/submit", "submit")}}
  6. -
-
- -

Valores

- -
-
"off"
-
The browser is not permitted to automatically enter or select a value for this field. It is possible that the document or application provides its own autocomplete feature, or that security concerns require that the field's value not be automatically entered. -
Note: In most modern browsers, setting autocomplete to "off" will not prevent a password manager from asking the user if they would like to save username and password information, or from automatically filling in those values in a site's login form. See the autocomplete attribute and login fields.
-
-
"on"
-
The browser is allowed to automatically complete the input. No guidance is provided as to the type of data expected in the field, so the browser may use its own judgement.
-
"name"
-
The field expects the value to be a person's full name. Using "name" rather than breaking the name down into its components is generally preferred because it avoids dealing with the wide diversity of human names and how they are structured; however, you can use the following autocomplete values if you do need to break the name down into its components: -
-
"honorific-prefix"
-
The prefix or title, such as "Mrs.", "Mr.", "Miss", "Ms.", "Dr.", or "Mlle.".
-
"given-name"
-
The given (or "first") name.
-
"additional-name"
-
The middle name.
-
"family-name"
-
The family (or "last") name.
-
"honorific-suffix"
-
The suffix, such as "Jr.", "B.Sc.", "PhD.", "MBASW", or "IV".
-
"nickname"
-
A nickname or handle.
-
-
-
"email"
-
An email address.
-
"username"
-
A username or account name.
-
"new-password"
-
A new password. When creating a new account or changing passwords, this is the "Enter your new password" field, as opposed to any "Enter your current password" field that might be present. This may be used by the browser both to avoid accidentally filling in an existing password and to offer assistance in creating a secure password.
-
"current-password"
-
The user's current password.
-
"organization-title"
-
A job title, or the title a person has within an organization, such as "Senior Technical Writer", "President", or "Assistant Troop Leader".
-
"organization"
-
A company or organization name, such as "Acme Widget Company" or "Girl Scouts of America".
-
"street-address"
-
A street address. This can be multiple lines of text, and should fully identify the location of the address within its second administrative level (typically a city or town), but should not include the city name, ZIP or postal code, or country name.
-
"address-line1", "address-line2", "address-line3"
-
Each individual line of the street address. These should only be present if the "street-address" is also present.
-
"address-level4"
-
The finest-grained {{anch("Administrative levels in addresses", "administrative level")}}, in addresses which have four levels.
-
"address-level3"
-
The third {{anch("Administrative levels in addresses", "administrative level")}}, in addresses with at least three administrative levels.
-
"address-level2"
-
The second {{anch("Administrative levels in addresses", "administrative level")}}, in addresses with at least two of them. In countries with two administrative levels, this would typically be the city, town, village, or other locality in which the address is located.
-
"address-level1"
-
The first {{anch("Administrative levels in addresses", "administrative level")}} in the address. This is typically the province in which the address is located. In the United States, this would be the state. In Switzerland, the canton. In the United Kingdom, the post town.
-
"country"
-
A country code.
-
"country-name"
-
A country name.
-
"postal-code"
-
A postal code (in the United States, this is the ZIP code).
-
"cc-name"
-
The full name as printed on or associated with a payment instrument such as a credit card. Using a full name field is preferred, typically, over breaking the name into pieces.
-
"cc-given-name"
-
A given (first) name as given on a payment instrument like a credit card.
-
"cc-additional-name"
-
A middle name as given on a payment instrument or credit card.
-
"cc-family-name"
-
A family name, as given on a credit card.
-
"cc-number"
-
A credit card number or other number identifying a payment method, such as an account number.
-
"cc-exp"
-
A payment method expiration date, typically in the form "MM/YY" or "MM/YYYY".
-
"cc-exp-month"
-
The month in which the payment method expires.
-
"cc-exp-year"
-
The year in which the payment method expires.
-
"cc-csc"
-
The security code for the payment instrument; on credit cards, this is the 3-digit verification number on the back of the card.
-
"cc-type"
-
The type of payment instrument (such as "Visa" or "Master Card").
-
"transaction-currency"
-
The currency in which the transaction is to take place.
-
"transaction-amount"
-
The amount, given in the currency specified by "transaction-currency", of the transaction, for a payment form.
-
"language"
-
A preferred language, given as a valid BCP 47 language tag.
-
"bday"
-
A birth date, as a full date.
-
"bday-day"
-
The day of the month of a birth date.
-
"bday-month"
-
The month of the year of a birth date.
-
"bday-year"
-
The year of a birth date.
-
"sex"
-
A gender identity (such as "Female", "Fa'afafine", "Male"), as freeform text without newlines.
-
"tel"
-
A full telephone number, including the country code. If you need to break the phone number up into its components, you can use these values for those fields: -
-
"tel-country-code"
-
The country code, such as "1" for the United States, Canada, and other areas in North America and parts of the Caribbean.
-
"tel-national"
-
The entire phone number without the country code component, including a country-internal prefix. For the phone number "1-855-555-6502", this field's value would be "855-555-6502".
-
"tel-area-code"
-
The area code, with any country-internal prefix applied if appropriate.
-
"tel-local"
-
The phone number without the country or area code. This can be split further into two parts, for phone numbers which have an exchange number and then a number within the exchange. For the phone number "555-6502", use "tel-local-prefix" for "555" and "tel-local-suffix" for "6502".
-
-
-
"tel-extension"
-
A telephone extension code within the phone number, such as a room or suite number in a hotel or an office extension in a company.
-
"impp"
-
A URL for an instant messaging protocol endpoint, such as "xmpp:username@example.net".
-
"url"
-
A URL, such as a home page or company web site address as appropriate given the context of the other fields in the form.
-
"photo"
-
The URL of an image representing the person, company, or contact information given in the other fields in the form.
-
- -

See the WHATWG Standard for more detailed information.

- -
-

Note: The autocomplete attribute also controls whether Firefox will — unlike other browsers — persist the dynamic disabled state and (if applicable) dynamic checkedness of an <input> across page loads. The persistence feature is enabled by default. Setting the value of the autocomplete attribute to off disables this feature. This works even when the autocomplete attribute would normally not apply to the <input> by virtue of its type. See {{bug(654072)}}.

-
- -

Administrative levels in addresses

- -

The four administrative level fields ("address-level1" through "address-level4") describe the address in terms of increasing levels of precision within the country in which the address is located. Each country has its own system of administrative levels, and may arrange the levels in different orders when addresses are written.

- -

"address-level1" always represents the broadest administrative division; it is the least-specific portion of the address short of the country name.

- -

Form layout flexibility

- -

Given that different countries write their address in different ways, with each field in different places within the address, and even different sets and numbers of fields entirely, it can be helpful if, when possible, your site is able to switch to the layout expected by your users when presenting an address entry form, given the country the address is located within.

- -

Variations

- -

The way each administrative level is used will vary from country to country. Below are some examples; this is not meant to be an exhaustive list.

- -

United States

- -

A typical home address within the United States looks like this:

- -

432 Anywhere St
- Exampleville CA 95555

- -

In the United States, the least-specific portion of the address is the state, in this case "CA" (the official US Postal Service shorthand for "California"). Thus "address-level1" is the state, or "CA" in this case.

- -

The second-least specific portion of the address is the city or town name, so "address-level2" is "Exampleville" in this example address.

- -

United States addresses do not use levels 3 and up.

- -

United Kingdom

- -

The UK uses one or two address levels, depending on the address. These are the post town and, in some instances, the locality.

- -

China

- -

China can use as many as three administrative levels: the province, the city, and the district.

diff --git a/files/es/web/html/element/shadow/index.html b/files/es/web/html/element/shadow/index.html deleted file mode 100644 index 7c5720124f..0000000000 --- a/files/es/web/html/element/shadow/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: -slug: Web/HTML/Element/shadow -translation_of: Web/HTML/Element/shadow -original_slug: Web/HTML/Elemento/Shadow ---- -

{{obsolete_header}}

- -

El HTML <shadow> element—es una parte absoluta de la suite tecnológica de Web Components —estaba destinado a ser utilizado como un shadow DOM {{glossary("insertion point")}}. Es posible que lo hayas usado si has creado varias root shadow bajo un shadow host. No es útil en HTML ordinario.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content categoriesTransparent content.
Permitted contentFlow content.
Tag omission{{no_tag_omission}}
Permitted parentsAny element that accepts flow content.
Permitted ARIA rolesNone
DOM interface{{domxref("HTMLShadowElement")}}
- -

Attributes

- -

This element includes the global attributes.

- -

Example

- -

Aquí está un ejemplo simple usando el  <shadow> element. Es un archivo HTML con todo lo necesario en él.

- -
-

Note: This is an experimental technology. For this code to work, the browser you display it in must support Web Components. See Enabling Web Components in Firefox.

-
- -
<html>
-  <head></head>
-  <body>
-
-  <!-- This <div> will hold the shadow roots. -->
-  <div>
-    <!-- This heading will not be displayed -->
-    <h4>My Original Heading</h4>
-  </div>
-
-  <script>
-    // Get the <div> above with its content
-    var origContent = document.querySelector('div');
-    // Create the first shadow root
-    var shadowroot1 = origContent.createShadowRoot();
-    // Create the second shadow root
-    var shadowroot2 = origContent.createShadowRoot();
-
-    // Insert something into the older shadow root
-    shadowroot1.innerHTML =
-      '<p>Older shadow root inserted by
-          &lt;shadow&gt;</p>';
-    // Insert into younger shadow root, including <shadow>.
-    // The previous markup will not be displayed unless
-    // <shadow> is used below.
-    shadowroot2.innerHTML =
-      '<shadow></shadow> <p>Younger shadow
-       root, displayed because it is the youngest.</p>';
-  </script>
-
-  </body>
-</html>
-
- -

If you display this in a web browser it should look like the following.

- -

shadow example

- -

Specifications

- -

This element is no longer defined by any specifications.

- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support35{{CompatGeckoDesktop("28")}}[1]{{CompatNo}}26{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support37{{CompatGeckoMobile("28")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] If Shadow DOM is not enabled in Firefox, <shadow> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 33 and is behind a preference, dom.webcomponents.enabled, which is disabled by default.

- -

See also

- - - -
{{HTMLRef}}
diff --git a/files/es/web/javascript/reference/global_objects/encodeuricomponent/index.html b/files/es/web/javascript/reference/global_objects/encodeuricomponent/index.html deleted file mode 100644 index e1e70a7747..0000000000 --- a/files/es/web/javascript/reference/global_objects/encodeuricomponent/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: encodeURIComponent -slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent -tags: - - JavaScript - - URI -translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent -original_slug: Web/JavaScript/Referencia/Objetos_globales/encodeURIComponent ---- -
{{jsSidebar("Objects")}}
- -

Resumen

- -

El método encodeURIComponent() codifica un componente URI (Identificador Uniforme de Recursos) al reemplazar cada instancia de ciertos caracteres por una, dos, tres o cuatro secuencias de escape que representan la codificación UTF-8 del carácter (solo serán cuatro secuencias de escape para caracteres compuestos por dos carácteres "sustitutos").

- -

Sintaxis

- -
encodeURIComponent(str);
- -

Parámetros

- -
-
str
-
Cadena. Un componente de un URI.
-
- -

Descripción

- -

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

- -

Note that an {{jsxref("Objetos_globales/URIError", "URIError")}} will be thrown if one attempts to encode a surrogate which is not part of a high-low pair, e.g.,

- -
// high-low pair ok
-alert(encodeURIComponent('\uD800\uDFFF'));
-
-// lone high surrogate throws "URIError: malformed URI sequence"
-alert(encodeURIComponent('\uD800'));
-
-// lone low surrogate throws "URIError: malformed URI sequence"
-alert(encodeURIComponent('\uDFFF'));
-
- -

To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.

- -

For application/x-www-form-urlencoded (POST), spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".

- -

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

- -
function fixedEncodeURIComponent (str) {
-  return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
-}
-
- -

Examples

- -

The following example provides the special encoding required within UTF-8 Content-Disposition and Link server response header parameters (e.g., UTF-8 filenames):

- -
var fileName = 'my file(2).txt';
-var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
-
-console.log(header);
-// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
-
-
-function encodeRFC5987ValueChars (str) {
-    return encodeURIComponent(str).
-        // Note that although RFC3986 reserves "!", RFC5987 does not,
-        // so we do not need to escape it
-        replace(/['()]/g, escape). // i.e., %27 %28 %29
-        replace(/\*/g, '%2A').
-            // The following are not required for percent-encoding per RFC5987,
-            //  so we can allow for a little better readability over the wire: |`^
-            replace(/%(?:7C|60|5E)/g, unescape);
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 3rd Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.1.3.4', 'encodeURIComponent')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}{{Spec2('ES6')}}
- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -

See also

- - diff --git a/files/es/web/javascript/reference/statements/with/index.html b/files/es/web/javascript/reference/statements/with/index.html deleted file mode 100644 index 9ad9f256c4..0000000000 --- a/files/es/web/javascript/reference/statements/with/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: with -slug: Web/JavaScript/Reference/Statements/with -translation_of: Web/JavaScript/Reference/Statements/with -original_slug: Web/JavaScript/Referencia/Sentencias/with ---- -
El uso de la declaración no es recomendado,  ya que puede ser el origen de los errores de confusión y problemas de compatibilidad. See the "Ambiguity Con" paragraph in the "Description" section below for details.
- -
{{jsSidebar("Statements")}}
- -

La sentencia with extiende el alcance de una cadena con la declaración.

- -

Sintaxis

- -
with (expresión) {
-  declaración
-}
-
- -
-
expresión
-
Añade la expresión dada a la declaración. Los parentesis alrededor de la expresión son necesarios.
-
declaración
-
Se puede ejecutar cualquier declaración. Para ejecutar varias declaraciónes, utilizar una declaración de bloque ({ ... }) para agrupar esas declaraciónes.
-
- -

Descripción

- -

JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a {{jsxref("ReferenceError")}} is thrown.

- -
Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.
- -

Performance pro & contra

- -

Pro: The with statement can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. The scope chain change required by 'with' is not computationally expensive. Use of 'with' will relieve the interpreter of parsing repeated object references. Note, however, that in many cases this benefit can be achieved by using a temporary variable to store a reference to the desired object.

- -

Contra: The with statement forces the specified object to be searched first for all name lookups. Therefore all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. Where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object.

- -

Ambiguity contra

- -

Contra: The with statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. So given this example:

- -
function f(x, o) {
-  with (o)
-    print(x);
-}
- -

Only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. If you forget to define x in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an error -- just unexpected results.

- -

Contra: Code using with may not be forward compatible, especially when used with something else than a plain object. Consider this example:

- -
-
function f(foo, values) {
-    with (foo) {
-        console.log(values)
-    }
-}
-
- -

If you call f([1,2,3], obj) in an ECMAScript 5 environment, then the values reference inside the with statement will resolve to obj. However, ECMAScript 6 introduces a values property on Array.prototype (so that it will be available on every array). So, in a JavaScript environment that supports ECMAScript 6, the values reference inside the with statement will resolve to [1,2,3].values.

-
- -

Examples

- -

Using with

- -

The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

- -
var a, x, y;
-var r = 10;
-
-with (Math) {
-  a = PI * r * r;
-  x = r * cos(PI);
-  y = r * sin(PI / 2);
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-with-statement', 'with statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.10', 'with statement')}}{{Spec2('ES5.1')}}Now forbidden in strict mode.
{{SpecName('ES3', '#sec-12.10', 'with statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.10', 'with statement')}}{{Spec2('ES1')}}Initial definition
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/es/web/mathml/authoring/index.html b/files/es/web/mathml/authoring/index.html deleted file mode 100644 index f9c30ff92c..0000000000 --- a/files/es/web/mathml/authoring/index.html +++ /dev/null @@ -1,415 +0,0 @@ ---- -title: Redacción de MathML -slug: Web/MathML/Authoring -translation_of: Web/MathML/Authoring ---- -

Este artículo explica como redactar funciones matemáticas utilizando el lenguaje MathML. Al igual que HTML, MathML puede describirse con etiquetas y atributos. HTML puede volverse interminable cuando tu documento contiene estructuras avanzadas como listas o tablas pero afortunadamente existen varios generadores, desde simple notaciones, editores WYSIWYG y otros Sistemas de Administración de Contenido (CMS) utilizados para la creación de páginas web.

- -

Las notaciones Matemáticas son aún más complejas con estructuras que contienen fracciones, raíces cuadradas o matrices que seguramente requerirán sus propias etiquetas. Como consecuencia, las buenas herramientas de redacción de MathML son importantes y más adelante describimos algunas opciones. En particular, el équipo MathML de Mozilla ha creado TeXZilla, un convertor de LaTeX a MathML compatible con Unicode, para ser utilizado en muchos scenari descrito ahí. Desde luego, la lista no es de ninguna manera definitiva y estás invitado a revisar la Lista de Software MathML de W3C donde puedes encontrar diferentes herramientas.

- -

Hay que señalar que por diseño, MathML está bien integrado en HTML5 y particularmente puedes utilizar las características Web comunes como CSS, DOM, Javascript o SVG. Esto está fuera del ámbito de este artículo pero cualquiera con conocimientos básicos de lenguajes Web será capaz de combinar fácilmente estas características con MathML. Revisa nuestros demos y referencias de MathML para más detalles.

- -

Fundamentos

- -

Utilizar MathML en páginas HTML

- -

Puedes utilizar MathML dentro de un documento HTML5:

- -
<!DOCTYPE html>
-<html>
-<head>
- <title>MathML in HTML5</title>
-</head>
-<body>
-
-  <h1>MathML in HTML5</h1>
-
-  <p>
-    Square root of two:
-    <math>
-      <msqrt>
-        <mn>2</mn>
-      </msqrt>
-    </math>
-  </p>
-
-</body>
-</html> 
- -

Content MathML no esta soportado por el navegador. Es recomendable convertir tu content MathML markup en Presentation MathML  antes de publicarlo, por ejemplo con la ayuda de la hoja de calculo  ctop.xsl  . Las herramientas mencionadas en esta pagina generan Presentation MathML.

- -

 

- -

Para navegadores sin soporte a MathML

- -

Desafortunadamente, algunos navegadores no son capaces  de  renderizar ecuaciones MathML o tienen un soporte limitado. Por lo tanto necesitará  usar  MathML polyfill para proveer el renderizado. Si necesita solo construcciones matematicas básicas tales como las utilizadas  en esta wiki de MDN entonces una pequeña hoja de cálculo mathml.css  podria  ser suficiente. Para usarlo, solo inserta una linea en el header de tu documento:

- -
<script src="http://fred-wang.github.io/mathml.css/mspace.js"></script>
- -

If you need more complex constructions, you might instead consider using the heavier MathJax library as a MathML polyfill:

- -
<script src="http://fred-wang.github.io/mathjax.js/mpadded.js"></script>
- -

Note that these two scripts perform feature detection of the mspace or mpadded elements (see the browser compatibility table on these pages). If you don't want to use this link to GitHub but instead to integrate these polyfills or others in your own project, you might need the detection scripts to verify the level of MathML support. For example the following function verifies the MathML support by testing the mspace element (you may replace mspace with mpadded):

- -
 function hasMathMLSupport() {
-  var div = document.createElement("div"), box;
-  div.innerHTML = "<math><mspace height='23px' width='77px'/></math>";
-  document.body.appendChild(div);
-  box = div.firstChild.firstChild.getBoundingClientRect();
-  document.body.removeChild(div);
-  return Math.abs(box.height - 23) <= 1  && Math.abs(box.width - 77) <= 1;
-}
- -

Alternatively, the following UA string sniffing will allow to detect the rendering engines with native MathML support (Gecko and WebKit). Note that UA string sniffing is not the most reliable method and might break from version to version:

- -
var ua = navigator.userAgent;
-var isGecko = ua.indexOf("Gecko") > -1 && ua.indexOf("KHTML") === -1 && ua.indexOf('Trident') === -1;
-var isWebKit = ua.indexOf('AppleWebKit') > -1 && ua.indexOf('Chrome') === -1;
- -

 

- -

Mathematical fonts

- -

Note: browsers can only use a limited set of mathematical fonts to draw stretchy MathML operators. However, implementation of the OpenType MATH table is in progress in Gecko & WebKit. This will provide a generic support for mathematical fonts and simplify the settings described in this section.

- -

To get a good mathematical rendering in browsers, some MathML fonts are required. It's a good idea to provide to your visitors a link to the MDN page that explains how to install MathML fonts. Alternatively, you can just make them available as Web fonts. You can get these fonts from the MathML-fonts add-on ; the xpi is just a zip archive that you can fetch and extract for example with the following command:

- -
wget https://addons.mozilla.org/firefox/downloads/latest/367848/addon-367848-latest.xpi -O mathml-fonts.zip; \
-unzip mathml-fonts.zip -d mathml-fonts
- -

Then copy the mathml-fonts/resource/ directory somewhere on your Web site and ensure that the woff files are served with the correct MIME type. Finally, include the mathml-fonts/resource/mathml.css style sheet in your Web pages, for example by adding the following rule to the default style sheet of your Web site:

- -
@import url('/path/to/resource/mathml.css');
- -

You then need to modify the font-family on the <math> elements and, for Gecko, the on ::-moz-math-stretchy pseudo element too. For example to use STIX fonts:

- -
math {
-  font-family: STIXGeneral;
-}
-
-::-moz-math-stretchy {
-  font-family: STIXNonUnicode, STIXSizeOneSym, STIXSize1, STIXGeneral;
-}
-
- -

Try the MathML torture test to compare the rendering of various fonts and the CSS rules to select them.

- -

Utilizar MathML en documentos XML (XHTML, EPUB, etc.)

- -

Si por alguna razón necesitas utilizar MathML en documentos XML, asegúrate de cumplir con los requisitos habituales: documentos bien realizados, el uso correcto de la especificación MIME, el prefijo MathML "http://www.w3.org/1998/Math/MathML" en la raíz <math>. Por ejemplo, la versión XHTML del ejemplo anterior luce de esta manera:
-  

- -
<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"
-  "http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
- <title>XHTML+MathML Example</title>
-</head>
-<body>
-
-<h1>XHTML+MathML Example</h1>
-
-  <p>
-    Square root of two:
-    <math xmlns="http://www.w3.org/1998/Math/MathML">
-      <msqrt>
-        <mn>2</mn>
-      </msqrt>
-    </math>
-  </p>
-
-</body>
-</html> 
- -

Note that if you use MathML as a standalone .mml or .svg documents or inside an EPUB book, it may not always be possible to use MathJax as a polyfill for rendering engines without MathML support. Hence whether MathML can be handled will vary according to the tools used to read these documents.

- -

Utilizar MathML en correos electrónicos

- -

Los clientes de correos modernos pueden enviar y recibir correos electrónicos en el formato HTML5 y por lo tanto pueden manejar expresiones de tipo MathML. Asegúrate de tener las opciones de "Enviar como HTML" y "Ver como HTML" habilitadas. En Thunderbird, puedes utilizar el comando "Insertar HTML" para pegar tu código HTML+MathML. MathBird es un complemento conveniente de Thunderbird para insertar este tipo de expresiones MathML utilizando la sintaxis AsciiMath.
-
- De nuevo, la forma en como MathML es manejada y la calidad de cómo se muestran estas expresiones depende del cliente de correo electrónico. Aún si tu navegador es compatible con MathML, tu servicio de correo electrónico puede evitar que envíes o recibas correos con expresiones MathML.

- -

Conversion from a Simple Syntax

- -

There are many simple notations (e.g. wiki or markdown syntaxes) to generate HTML pages. The same is true for MathML: for example ASCII syntaxes as used in calculators or the more powerful LaTeX language, very popular among the scientific community. In this section, we present some of these tools to convert from a simple syntax to MathML.

- - - -

Client-side Conversion

- -

In a Web environment, the most obvious method to convert a simple syntax into a DOM tree is to use Javascript and of course many libraries have been developed to perform that task.

- - - -

TeXZilla has an <x-tex> custom element, that can be used to write things like

- -
<x-tex>\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1</x-tex>
- -

and get it automatically converted into MathML. This is still a work-in-progress, but could be improved in the future thanks to Web Components and shadow DOM. Alternatively, you can use the more traditional Javascript parsing of expressions at load time as all the other tools in this section do.

- -

One simple client-side conversion tools is ASCIIMathML. Just download the ASCIIMathML.js script and copy it to your Web site. Then on your Web pages, add a <script> tag to load ASCIIMathML and the mathematical expressions delimited by ` (grave accent) will be automatically parsed and converted to MathML:

- -
<html>
-<head>
-...
-<script type="text/javascript" src="ASCIIMathML.js"></script>
-...
-</head>
-<body>
-...
-<p>blah blah `x^2 + y^2 = r^2` blah ...
-...
- -

LaTeXMathML is a similar script that allows to parse more LaTeX commands. The installation is similar: copy LaTeXMathML.js and LaTeXMathML.standardarticle.css, add links in the header of your document and the LaTeX content of your Web page marked by the "LaTeX" class will be automatically parsed and converted to HTML+MathML:

- -
<head>
-...
-<script type="text/javascript" src="LaTeXMathML.js"></script>
-<link rel="stylesheet" type="text/css" href="LaTeXMathML.standardarticle.css" />
-...
-</head>
-
-<body>
-...
-
-<div class="LaTeX">
-\documentclass[12pt]{article}
-
-\begin{document}
-
-\title{LaTeXML Example}
-\maketitle
-
-\begin{abstract}
-This is a sample LaTeXML document.
-\end{abstract}
-
-\section{First Section}
-
-  $ \sum_{n=1}^{+\infty} \frac{1}{n^2} = \frac{\pi^2}{6} $
-
-\end{document}
-</div>
-...
- -

jqMath is another script to parse a simple LaTeX-like syntax but which also accepts non-ASCII characters like  √{∑↙{n=1}↖{+∞} 6/n^2} = π  to write n = 1 + 6 n 2 = π . The installation is similar: download and copy the relevant Javascript and CSS files on your Web site and reference them in your page header (see the COPY-ME.html file from the zip archive for an example). One of the advantage of jqMath over the previous scripts is that it will automatically add some simple CSS rules to do the mathematical layout and make the formulas readable on browsers with limited MathML support.

- -

Another way to work around the lack of MathML support in some browsers is to use MathJax. However, note that you may find conflicts and synchronization issues between MathJax and the Javascript libraries previously mentioned. So if you really want to use MathJax as a MathML polyfill, you'd better use its own LaTeX/ASCIIMath parsers too. Note that on the one hand MathJax has better parsing and rendering support but on the other hand it is much bigger, more complex and slower than the previous Javascript libraries. Fortunately, you can use MathJax's CDN so that you don't need to install it on your Web server. Also, the slowest part of MathJax is currently its HTML-CSS / SVG output modes so we recommend to use the Native MathML output for Gecko-based browsers. Hence a typical configuration to use the AMS-LaTeX input is:

- -
...
-    <script type="text/x-mathjax-config">
-      MathJax.Hub.Config({
-        MMLorHTML: { prefer: { Firefox: "MML" } }
-      });
-    </script>
-    <script type="text/javascript"
-            src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
-   </script>
-  </head>
-  <body>
-   \[ \tau = \frac{x}{y} + \sqrt{3} \]
-...
- -

Note that the dollar delimiters are not used by default. To use the ASCIIMathML input instead, just replace TeX-AMS-MML_HTMLorMML by AM-MML_HTMLorMML.  MathJax has many other features, see the MathJax documentation for further details.

- -

Command-line Programs

- -

An alternative way is to parse the simple syntax before publishing your web pages. That is, you use command-line programs to generate them and publish these static pages on your server.

- - - -

TeXZilla can be used from the command line and will essentially have the same support as itex2MML described below. However, the stream filter behavior is not implemented yet.

- -

If you only want to parse simple LaTeX mathematical expressions, you might want to try tools like itex2MML or Blahtex. The latter is often available on Linux distributions. Let's consider the former, which was originally written by Paul Gartside at the beginning of the Mozilla MathML project and has been maintained by Jacques Distler since then. It's a small stream filter written in C/C++ and generated with flex and bison ; in particular it is very fast. Install flex/bison as well as the classical compiler and make tools. On Unix, you can then download itex2MML, build and install it:

- -
wget http://golem.ph.utexas.edu/~distler/blog/files/itexToMML.tar.gz; \
-tar -xzf itexToMML.tar.gz; \
-cd itex2MML/itex-src;
-make
-sudo make install
- -

Now suppose that you have a HTML page with TeX fragments delimited by dollars:

- -
input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}$</p>
-  <p>$$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $$</p>
-</body>
-</html>lt;/p>
-  <p>$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $</p>
-</body>
-</html>lt;/p>
-  <p>$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $</p>
-</body>
-</html>lt;/p>
-  <p>$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}$</p>
-  <p>$$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $$</p>
-</body>
-</html>lt;/p>
-  <p>$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $</p>
-</body>
-</html>lt;/p>
-</body>
-</html>
- -

Then to generate the HTML page input.html with TeX expressions replaced by MathML expressions, just do

- -
cat input.html | itex2MML > output.html
- -

There are even more sophisticated tools to convert arbitrary LaTeX documents into HTML+MathML. For example TeX4ht is often included in TeX distributions and has an option to use MathML instead of PNG images. This command will generate an XHTML+MathML document foo.xml from a foo.tex LaTeX source:

- -
   mk4ht mzlatex foo.tex # Linux/Mac platforms
-   mzlatex foo.tex       # Windows platform
-
- -

LaTeXML is another tool that is still actively developed but the release version is rather old, so you'd better install the development version. In particular, this version can generate HTML5 and EPUB documents. Here is the command to execute in order to create a foo.html Web page from the foo.tex LaTeX source:

- -
  latexml --dest foo.xml foo.tex
-  latexmlpost --dest foo.html --format=html5 foo.xml
-
- -

If you want to have a MathJax fallback for non-Gecko browsers, copy the Javascript lines given above into a mathjax.js file and use the --javascript parameter to tell LaTeXML to include that file:

- -
  latexmlpost --dest foo.html --format=html5 --javascript=mathjax.js foo.xml
-
- -

If your LaTeX document is big, you might want to split it into several small pages rather putting everything in a single page. This is especially true if you use the MathJax fallback above, since in that case MathJax will take a lot of time to render the equations in non-Gecko browsers. Use the --splitat parameter for that purpose. For example, this will split the pages at the \section level:

- -
  latexmlpost --dest foo.html --format=html5 --splitat=section foo.xml
-
- -

Finally, to generate an EPUB document, you can do

- -
  latexmlc --dest foo.epub --splitat=section foo.xml
-
- -

Server-side Conversion

- - - -

TeXZilla can be used as a Web server in order to perform server-side LaTeX-to-MathML conversion. LaTeXML can also be used as a deamon to run server-side. Mathoid is another tool based on MathJax that is also able to perform additional MathML-to-SVG conversion.

- -

Instiki is a Wiki that integrates itex2MML to do server-side conversion. In future versions, MediaWiki will support server-side conversion too.

- -

Graphical Interface

- -

Input Box

- -

TeXZilla has several interfaces, including a CKEditor plugin used on MDN, an online demo, a Firefox add-on or a FirefoxOS Webapp. Abiword contains a small equation editor, based on itex2MML. Bluegriffon is a mozilla-based Wysiwyg HTML editor and has an add-on to insert MathML formulas in your document, using ASCII/LaTeX-like syntax.

- -

BlueGriffon

- -

WYSIYWG Editors

- -

Firemath is an extension for Firefox that provides a WYSIWYG MathML editor. A preview of the formula is displayed using the rendering engine of Mozilla. The generated MathML code is available at the bottom. Use the text field for token elements and buttons to build advanced constructions. Once you are done, you can save your document as a XHTML page.

- -

OpenOffice and LibreOffice have an equation editor (File → New → Formula). It is semi-WYSIWYG: you enter the source of the formula using the equation panel/keyboard and a preview of the formula is regularly refreshed. The editor uses its own syntax "StarMath" for the source but MathML is also generated when the document is saved. To get the MathML code, save the document as mml and open it with any text editor. Alternatively, you can extract the odf file (which is actually a zip archive) and open an xml file called content.xml.

- -

Open Office Math

- -

Amaya is the W3C's web editor, which is able to handle MathML inside XHTML documents. Use the Elements and the Special Chars panels to create various advanced mathematical constructs. Simple text such as a+2 is automatically parsed and the appropriate MathML markup is generated. Once you are done, you can directly save your XHTML page and open it in Mozilla.

- -

Optical Character & Handwriting Recognition

- -

Inftyreader is able to perform some Optical Character Recognition, including translation of mathematical equations into MathML. Other tools can do handwriting recognition such as the Windows Math Input Panel

- -

or the online converter Web Equation.

- -

Original Document Information

- -
-
    -
  • Author(s): Frédéric Wang
  • -
  • Other Contributors: Florian Scholz
  • -
  • Last Updated Date: April 2, 2011
  • -
  • Copyright Information: Portions of this content are © 2010 by individual mozilla.org contributors; content available under a Creative Commons license | Details.
  • -
-
- -

 

diff --git a/files/es/web/mathml/authoring/openoffice.png b/files/es/web/mathml/authoring/openoffice.png deleted file mode 100644 index 4876bc83df..0000000000 Binary files a/files/es/web/mathml/authoring/openoffice.png and /dev/null differ diff --git a/files/es/web/media/formats/index.html b/files/es/web/media/formats/index.html deleted file mode 100644 index b11ddc3580..0000000000 --- a/files/es/web/media/formats/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: 'Media type and format guide: image, audio, and video content' -slug: Web/Media/Formats -tags: - - API - - Audio - - Codecs - - Containers - - File Types - - Files - - Filetypes - - Landing - - Media - - NeedsTranslation - - TopicStub - - Types - - Video - - Web - - formats -translation_of: Web/Media/Formats ---- -

{{QuickLinksWithSubpages("/en-US/docs/Web/Media")}}

- -

Since nearly its beginning, the web has included support for some form of visual media presentation. Originally, these capabilities were limited, and were expanded organically, with different browsers finding their own solutions to the problems around including still and video imagery on the web. The modern web has powerful features to support the presentation and manipulation of media, with several media-related APIs supporting various types of content. Generally, the media formats supported by a browser are entirely up to the browser's creators, which can complicate the work of a web developer.

- -

This guide provides an overview of the media file types, {{Glossary("codec", "codecs")}}, and algorithms that may comprise media used on the web. It also provides browser support information for various combinations of these, and suggestions for prioritization of formats, as well as which formats excel at specific types of content.

- -
-
-

References

- -

Images

- -
-
Image file type and format guide
-
Covers support of image file types and content formats across the major web browsers, as well as providing basic information about each type: benefits, limitations, and use cases of interest to web designers and developers.
-
Image file types for web designers
-
Fundamental information about the various image file types that may be useful for web designers, including best practices and use cases for each type, and guidelines for choosing the right image file format for specific types of content.
-
- -

Media file types and codecs

- -
-
Media containers (file types)
-
A guide to the file types that contain media data. Some are audio-specific, while others may be used for either audio or combined audiovisual content such as movies. Includes overviews of each of the file types supported by the major web browsers, along with browser support information and supported features.
-
- -
-
Web audio codec guide
-
A guide to the audio codecs allowed for by the common media containers, as well as by the major browsers. Includes benefits, limitations, key specifications and capabilities, and use cases. It also covers each browser's support for using the codec in given containers.
-
Web video codec guide
-
This article provides basic information about the video codecs supported by the major browsers, as well as some that are not commonly supported but that you might still run into. It also covers codec capabilities, benefits, limitations, and browser support levels and restrictions.
-
The "codecs" parameter in common media types
-
When specifying the MIME type describing a media format, you can provide details using the codecs parameter as part of the type string. This guide describes the format and possible values of the codecs parameter for the common media types.
-
Codecs used by WebRTC
-
WebRTC doesn't use a container, but instead streams the encoded media itself from peer to peer using {{domxref("MediaStreamTrack")}} objects to represent each audio or video track. This guide discusses the codecs commonly used with WebRTC.
-
-
- -
-

Guides

- -

Concepts

- -
-
Digital audio concepts
-
An introduction to how audio is converted into digital form and stored for use by computers. It explains basic concepts about how audio is sampled, as well as concepts such as sample rate, audio frames, and audio compression.
-
Digital video concepts
-
A guide to fundamental concepts involved with digital video as used on the web, including basics about color formats, chroma subsampling, how human perception influences video coding, and so forth.
-
- -

Tutorials and how-tos

- -
-
Learning: Video and audio content
-
This tutorial introduces and details the use of media on the web.
-
Handling media support issues in web content
-
In this guide, we look at how to build web content that maximizes quality or performance while providing the broadest possible compatibility, by choosing media formats wisely, and offering fallbacks and alternate formats where it would be helpful.
-
- -

Other topics

- -
-
Media Capabilities API
-
The Media Capabilities API lets you discover the encoding and decoding capabilities of the device your app or site is running on. This lets you make real-time decisions about what formats to use and when.
-
-
-
diff --git a/files/es/web/svg/element/foreignobject/index.html b/files/es/web/svg/element/foreignobject/index.html deleted file mode 100644 index ea64360cbb..0000000000 --- a/files/es/web/svg/element/foreignobject/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: foreignObject -slug: Web/SVG/Element/foreignObject -translation_of: Web/SVG/Element/foreignObject ---- -
{{SVGRef}}
- -

El elemento foreignObject permite la inclusión de un namespace XML externo que tiene su contenido gráfico dibujado por un diferente user-agent. El contenido gráfico externo incluido está sujeto a las transformaciones SVG y composición.

- -

The contents of foreignObject are assumed to be from a different namespace. Any SVG elements within a foreignObject will not be drawn, except in the situation where a properly defined SVG subdocument with a proper xmlns attribute specification is embedded recursively. One situation where this can occur is when an SVG document fragment is embedded within another non-SVG document fragment, which in turn is embedded within an SVG document fragment (e.g., an SVG document fragment contains an XHTML document fragment which in turn contains yet another SVG document fragment).

- -

Usually, a foreignObject will be used in conjunction with the {{ SVGElement("switch") }} element and the {{ SVGAttr("requiredExtensions") }} attribute to provide proper checking for user agent support and provide an alternate rendering in case user agent support is not available.

- -

Usage context

- -

{{svginfo}}

- -

Example

- -
<svg width="400px" height="300px" viewBox="0 0 400 300"
-     xmlns="http://www.w3.org/2000/svg">
-  <desc>This example uses the 'switch' element to provide a
-        fallback graphical representation of a paragraph, if
-        XHTML is not supported.</desc>
-
-  <!-- The 'switch' element will process the first child element
-       whose testing attributes evaluate to true.-->
-  <switch>
-
-    <!-- Process the embedded XHTML if the requiredExtensions attribute
-         evaluates to true (i.e., the user agent supports XHTML
-         embedded within SVG). -->
-    <foreignObject width="100" height="50"
-                   requiredExtensions="http://www.w3.org/1999/xhtml">
-      <!-- XHTML content goes here -->
-      <body xmlns="http://www.w3.org/1999/xhtml">
-        <p>Here is a paragraph that requires word wrap</p>
-      </body>
-    </foreignObject>
-
-    <!-- Else, process the following alternate SVG.
-         Note that there are no testing attributes on the 'text' element.
-         If no testing attributes are provided, it is as if there
-         were testing attributes and they evaluated to true.-->
-    <text font-size="10" font-family="Verdana">
-      <tspan x="10" y="10">Here is a paragraph that</tspan>
-      <tspan x="10" y="20">requires word wrap.</tspan>
-    </text>
-  </switch>
-</svg>
-
- -

Attributes

- -

Global attributes

- - - -

Specific attributes

- - - -

DOM Interface

- -

This element implements the SVGForeignObjectElement interface.

- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.01.9{{ CompatNo() }}2.03.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}2.0{{ CompatNo() }}2.03.0
-
- -

The chart is based on these sources.

diff --git a/files/es/web/xslt/element/number/index.html b/files/es/web/xslt/element/number/index.html deleted file mode 100644 index 519c2361c2..0000000000 --- a/files/es/web/xslt/element/number/index.html +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: number -slug: Web/XSLT/Element/number -tags: - - Todas_las_Categorías - - XSLT -translation_of: Web/XSLT/Element/number -original_slug: Web/XSLT/number ---- -

{{XsltRef}}

- -

El elemento <xsl:number> hace conteos secuenciales. También puede ser usado para darle formato a los números.

- -

Sintaxis

- -
<xsl:number
-	count=EXPRESION
-	level="single" | "multiple" | "any"
-	from=EXPRESION
-	value=EXPRESION
-	format=FORMAT-STRING
-	lang=XML:LANG-CODE
-	letter-value="alphabetic" | "traditional"
-	grouping-separator=CARACTER
-	grouping-size=NUMERO  />
- -

Atributos requeridos

- -

Ninguno.

- -

Atributos opcionales

- -
-
count
-
Indica que es lo que debe ser numerado de manera secuencial. Usa una expresión XPath.
-
- -
-
level
-
Define cuantos niveles del documento deben ser tomados en cuenta para generar la secuencia numérica. Tiene 3 valores permitidos: single, multiple, y any. El valor por preestablecido es single:
-
- -
-
-
-
single
-
Numera los nodos hermanos de manera secuencia, como en los listados. ... CONTINUAR DESDE AQUÍ...
-
Numbers sibling nodes sequentially, as in the items in a list. The processor goes to the first node in the ancestor-or-self axis that matches the count attribute and then counts that node plus all its preceding siblings (stopping when it reaches a match to the from attribute, if there is one) that also match the count attribute.If no match is found, the sequence will be an empty list.
-
-
-
- -
-
-
-
multiple
-
Numbers nodes as a composite sequence that reflects the hierarchic position of the node, e.g. 1.2.2.5. (The nested format can be specified with the format attribute, e.g. A.1.1). The processor looks at all ancestors of the current node and the current node itself, stopping when it reaches a match for the from attribute, if there is one. For each node in this list that matches the count attribute, the processor counts how many preceding matching siblings it has, and adds one for the node itself. If no match is found, the sequence will be an empty list.
-
-
-
- -
-
-
-
any (Not supported at this time.)
-
Numbers all matching nodes, regardless of level, sequentially. The ancestor, self, and preceding axes are all considered. The processor starts at the current node and proceeds in reverse document order, stopping if it reaches a match to any from attribute. If no match to the count attribute is found, the sequence will be an empty list. This level is not supported at this time.
-
-
-
- -
-
from
-
Specifies where the numbering should start or start over. The sequence begins with the first descendant of the node that matches the from attribute.
-
- -
-
value
-
Applies a given format to a number. This is a quick way to format a user-supplied number (as opposed to a node sequence number) in any of the standard <xsl:number> formats.
-
- -
-
format
-
Defines the format of the generated number:
-
- -
-
-
-
format="1"
-
1 2 3 . . . (This is the only format supported at this time)
-
-
-
- -
-
-
-
format="01"
-
01 02 03 . . . 09 10 11 . . .
-
-
-
- -
-
-
-
format="a"
-
a b c . . .y z aa ab . . .
-
-
-
- -
-
-
-
format="A"
-
A B C . . . Y Z AA AB . . .
-
-
-
- -
-
-
-
format="i"
-
i ii iii iv v . . .
-
-
-
- -
-
-
-
format="I"
-
I II III IV V . . .
-
-
-
- -
-
lang (Not supported at this time.)
-
Specifies which language's alphabet should be used in letter-based numbering formats.
-
- -
-
letter-value
-
Disambiguates between numbering sequences that use letters. Some languages have more than one numbering system that use letters. If both systems begin with the same token, ambiguity can arise. This attribute can have the value "alphabetic" or "traditional". The default is "alphabetic".
-
- -
-
grouping-separator
-
Specifies what character should be used as the group (e.g. thousands) separator. The default is the comma (,).
-
- -
-
grouping-size
-
Indicates the number of digits that make up a numeric group. The default value is "3".
-
- -

Type

- -

Instruction, appears within a template.

- -

Defined

- -

XSLT, section 7.7

- -

Gecko support

- -

Partial support. See comments above.

-- cgit v1.2.3-54-g00ecf