While researching my answer to Jon's question I came across the following rabbinic interpretation (Babylonian talmud, Yevamot 34b):
[The source for] Onan's [guilt] may well be traced, for it is written in Scripture, That he spilt it on the ground; whence however, [that of] Er? -R. Nahman b. Isaac replied: It is written, And He slew him also, he also died of the same death.
The rabbis understand "slew him also", without elaboration, to mean "slew him also for the same reason": Er prevented Tamar from becoming pregnant.
Why would he do that? The talmud continues:
[The reason for] Onan's [action] may well be understood, because he knew that the seed would not be his; but why did Er act in such a manner? — In order that she might not conceive and thus lose some of her beauty.
So according to the rabbis Er and Onan both prevented Tamar from conceiving; they acted for different (selfish) reasons, but this act against their wife was deserving of punishment.
Please note: This answer was written for a neutral, academic audience
and is not intended to be interpreted in the context of a religious
belief or doctrine.